国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 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嗎?


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 额济纳旗| 民乐县| 方城县| 太和县| 霍州市| 晋城| 察隅县| 南部县| 大洼县| 揭东县| 广东省| 云阳县| 玉环县| 郴州市| 白朗县| 吴江市| 巴南区| 仁寿县| 老河口市| 泽库县| 荥经县| 余干县| 武汉市| 越西县| 吉木乃县| 杭锦后旗| 沂源县| 三亚市| 弥渡县| 新安县| 文成县| 荣昌县| 淮滨县| 紫金县| 永川市| 武邑县| 广东省| 宕昌县| 辽阳县| 行唐县| 丹巴县|