排序简单 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 位运动员的获奖情况。

分析

  • 使用map存储排序后的元素数值与位次的映射关系。
  • 数组下标是从 0 开始的,但是排名是从 1 开始的
class Solution {
    
    
    public String[] findRelativeRanks(int[] score) {
    
    
        String[] rank = new String[]{
    
    "Gold Medal","Silver Medal","Bronze Medal"};
        int[] cp = score.clone();
        Arrays.sort(cp);
        // Arrays.sort(cp,new Comparator<Integer>(){
    
    
        //     public int compare(Integer a, Integer b){
    
    
        //         return b -a;
        //     }
        // });
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0; i < cp.length; i++){
    
    
            map.put(cp[i],cp.length-i-1);
        }
        String[] ans = new String[cp.length];
        for(int i = 0; i < score.length; i++){
    
    
            int tmp = map.get(score[i]);
            ans[i] = tmp < 3 ? rank[tmp] : 1+tmp+"";
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43260719/article/details/121686831