首页 > 网站 > WEB开发 > 正文

LeetCode解题笔记(2)

2024-04-27 15:19:15
字体:
来源:转载
供稿:网友

上次Two Sum的思考不对 因为题目要求返回原数组的序列,而排序之后,序列会发生变化,所以还需要将原来的数组复制到另一个数组中才行。今天就碰到了类似的题目。

506. Relative Ranks

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example 1:

Input: [5, 4, 3, 2, 1]Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". For the left two athletes, you just need to output their relative ranks according to their scores.

题目大意:给一个数组,为几个运动员的分数,返回他们的排名,如果前三名应该为"Gold Medal", "Silver Medal", "Bronze Medal",否则是数字名次,保证所有的分数不重复

思路还是简单粗暴:新建一个数组并把当前数组复制过去,新数组排序(注意高分在前面),然后遍历数组,找到老数组中的元素依次对应新数组中的第几个,将序列号以字符串的形式赋给老数组对应的元素。还要将前三名分别对应题目中的金银铜。

代码:

var findRelativeRanks = function(nums) {    var newnums = [];    for(var p=0,q=0;p<nums.length;p++,q++){newnums[q] = nums[p];}    newnums = newnums.sort(function(a,b){        return b-a;    });    for(var i = 0;i < nums.length; i++){        for(var j = 0; j < newnums.length; j++){            if(newnums[j] == nums[i]){                nums[i] = (j+1).toString();                break;            }        }    }        for(var n = 0; n < nums.length;n++){        if(nums[n] == "1"){            nums[n] = "Gold Medal";        }else if(nums[n] == "2"){            nums[n] = "Silver Medal";        }else if(nums[n] == "3"){            nums[n] = "Bronze Medal";        }    }    return nums;};

344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:Given s = "hello", return "olleh".

这题跟上次Reverse Integer差不多,还是借助Array.reverse()。

/** * @param {string} s * @return {string} */var reverseString = function(s) {    s = s.split("").reverse().join("").toString();    return s;};不知道为什么今天LeetCode网站特别慢。。需要用vpn吗?


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表