leetcode刷题第二天--相对名次(简单题)

给你一个长度为 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] 。

法一:逐个比较并把每名选手对应的排名存放至orders数组之中,缺点:用时以及内存占用都过大。
优点:无脑

public String[] findRelativeRanks(int[] score) {
        String[] orders = new String[score.length];
        int [] scores = new int[score.length];
        //数组拷贝
        //五个参数:拷贝源,源起始,拷贝目标,目标起始,拷贝长度
        System.arraycopy(score,0,scores,0,score.length);
        //排序
        Arrays.sort(scores);
        for (int i =score.length-1;i>=0;i--){
            for(int j = 0;j<score.length;j++){
                if(score[j]==scores[i]){
                    if(i<=score.length-4){
                        orders[j] = ""+(score.length-i);
                    }else if(i==score.length-1){
                        orders[j]="Gold Medal";
                    }else if(i==score.length-2){
                        orders[j]="Silver Medal";
                    }else{
                        orders[j]="Bronze Medal";
                    }
                }
            }
        }
        return orders;
    }

在这里插入图片描述
法二:通过HashMap来排序

public String[] findRelativeRanks(int[] score) {
    //这里同法一
    int[] scores=new int[score.length];
    System.arraycopy(score,0,scores,0,score.length);
     Arrays.sort(scores);
    //  创建一个HashMap建立联系
    Map<Integer,Integer> map=new HashMap<Integer,Integer> ();
    for(int i=0;i<score.length;i++){
        map.put(scores[i],score.length-i);
    }

    String[] str=new String[score.length];
    for(int i=0;i<score.length;i++){
        int mc=map.get(score[i]);
        if(mc==1){
            str[i]="Gold Medal";
        }else if(mc==2){
            str[i]="Silver Medal";
        }else if(mc==3){
            str[i]="Bronze Medal";
        }else{
             str[i]=mc+"";
        }
    }

    return str;

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值