go语言题解LeetCode506相对名次示例详解
目录
- 一 描述
- 二 分析
- 三 答案
一 描述
506. 相对名次
给你一个长度为 n 的整数数组 score ,其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。
运动员将根据得分 决定名次 ,其中名次第 1 的运动员得分最高,名次第 2 的运动员得分第 2 高,依此类推。运动员的名次决定了他们的获奖情况:
- 名次第 1 的运动员获金牌 "Gold Medal" 。
- 名次第 2 的运动员获银牌 "Silver Medal" 。
- 名次第 3 的运动员获铜牌 "Bronze Medal" 。
- 从名次第 4 到第 n 的运动员,只能获得他们的名次编号(即,名次第 x 的运动员获得编号 "x")。
使用长度为 n 的数组 answer 返回获奖,其中 answer[i] 是第 i 位运动员的获奖情况。
示例 1:
输入:score = [5,4,3,2,1] 输出:["Gold Medal","Silver Medal","Bronze Medal","4","5"] 解释:名次为 [1st, 2nd, 3rd, 4th, 5th] 。
示例 2:
输入:score = [10,3,8,9,4] 输出:["Gold Medal","5","Bronze Medal","Silver Medal","4"] 解释:名次为 [1st, 5th, 3rd, 2nd, 4th] 。
提示:
n == score.length
1 <= n <= 10^4
0 <= score[i] <= 10^6
score 中的所有值 互不相同
二 分析
本题以map映射求解,首先把所有的字符串分别添加到指定map集合中去,并依次给予对应的索引,随后对字符串数组进行从大到小排序,并依次从map集合中由键找值,并把该值给到提前创建的字符串数组中作为索引,从大到小依次赋予“Gold Medal”、“Silver Medal”、“Bronze Medal”以及3、4、5...
三 答案
class Solution {
public String[] findRelphpativeRanks(int[] nums) {
if(nums.length==1) {
return new String[]{"Gold Mejavascriptdal"};
}
String[] arr = new String[nums.length];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int count = 0;
for(int i = 0,j=0;i<nums.length && pythonj<nums.length;i++,j++) {
map.put(nums[i],j);
}
Arrays.sort(nums);
for(int i = 0;i<nums.length/2;i++) {
int temp = nums[nums.length-i-1];
nums[nums.length-i-1] = nums[i];
nums[i] = temp;
}
if(nums.length==2) {
arr[map.get(nums[0])] = "Gold Medal";
arr[map.get(nums[1])] = "Silver Medal";
return arr;
}
arr[map.get(nums[0])] = "Gold Medal";
arr[map.get(nums[1])] = "Silver Medal";
开发者_C学习 arr[map.get(nums[2])javascript] = "Bronze Medal";
for(int i = 3;i<nums.length;i++) {
arr[map.get(nums[i])] = i+1+"";
}
return arr;
}
}
以上就是go语言题解LeetCode506相对名次示例详解的详细内容,更多关于go语言题解相对名次的资料请关注我们其它js相关文章!
加载中,请稍侯......
精彩评论