上次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嗎?
新聞熱點
疑難解答