LeetCode解題筆記(2)

上次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嗎?


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章