LeetCode506. 相对名次
给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”(“Gold Medal”, “Silver Medal”, “Bronze Medal”)。
(注:分数越高的选手,排名越靠前。)
示例:
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
解题思路:
1,先用哈希表将数组中每个元素的位置进行存储。
2,进行数组的排序。
3,从后往前进行遍历,并计数,后三个元素将[“Gold Medal”,“Silver Medal”,“Bronze Medal”]进行相应替换,取出哈希表中对应元素的位置,对新的String数组的赋值。
解题代码:
class Solution {
public String[] findRelativeRanks(int[] score) {
Map<Integer,Integer> m=new HashMap<>();
for(int a=0;a<score.length;a++){
//存位置
m.put(score[a],a);
}
int count=0;
Arrays.sort(score);
String[] result=new String[score.length];
for(int b=result.length-1;b>=0;b--){
count++;
if(b==result.length-1){
result[m.get(score[b])]="Gold Medal";
}else if(b==result.length-2){
result[m.get(score[b])]="Silver Medal";
}else if(b==result.length-3){
result[m.get(score[b])]="Bronze Medal";
}else{
result[m.get(score[b])]=count+"";
}
}
return result;
}
}