码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 506. Relative Ranks

时间:2020-01-14 09:30:02      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:and   class   else   个数   dex   题意   i++   tostring   top   

相对排名。题意很简单,给一个数组表示一堆运动员的名次,请输出他们的相对排名,前三名需要有一些改动。例子如下,

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.

思路是先对input排序,然后对前三名做一些变动,其余名次不变。

时间O(n)

空间O(n)

 1 /**
 2  * @param {number[]} nums
 3  * @return {string[]}
 4  */
 5 var findRelativeRanks = function(nums) {
 6     let sortArray = nums.slice();
 7     sortArray.sort((a, b) => b - a);
 8     let res = [];
 9     for (let i = 0; i < nums.length; i++) {
10         const j = sortArray.indexOf(nums[i]);
11         if (j === 0) {
12             res.push(‘Gold Medal‘);
13         } else if (j === 1) {
14             res.push(‘Silver Medal‘);
15         } else if (j === 2) {
16             res.push(‘Bronze Medal‘);
17         } else {
18             res.push((j + 1).toString());
19         }
20     }
21     return res;
22 };

[LeetCode] 506. Relative Ranks

标签:and   class   else   个数   dex   题意   i++   tostring   top   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12190145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!