[LeetCode] 506. Relative Ranks
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 506. Relative Ranks相关的知识,希望对你有一定的参考价值。
相对排名。题意很简单,给一个数组表示一堆运动员的名次,请输出他们的相对排名,前三名需要有一些改动。例子如下,
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的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode&Python] Problem 506. Relative Ranks
[LeetCode] 506. Relative Ranks
leetcode 506. ????????????(Relative Ranks)