LC506.相对名次

题目

查看题目

解题思路

注意问题:

  • 给定的sorce数组不是排好序的,不能直接根据数组顺序进行名次的分配。
  • 前三名又额外的荣誉称号,要单独列出来。
    主要思路:
  • 设置一个Map,使用Map将数组中的数据存储起来,将成绩作为Key,将索引作为Value进行存储。
  • 因为Arrays中的sort函数只能从小到大排序,所以稍微改了一下冒泡,使数组从大到小排列。
  • 遍历数组,使用switch进行前三名荣誉的判别。遍历的时候将排序后数组的值作为Mapget()的参数找到该成绩在原数组的位置。
  • 创建一个String类型的数组,根据上面get()查询到的真正索引位置,将相关的荣誉加入到String数组中,完成任务。。。

代码

class Solution {
    public String[] findRelativeRanks(int[] score) {
        String[] str = new String[score.length];
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < score.length; i++) {
            //成绩作为key,索引作为value
            map.put(score[i], i);
        }
        sort1(score);
        // for (int i : score) {
        //     System.out.print(i + " ");
        // }
        for (int i = 0; i < score.length; i++) {
            if (i < 3) {
                switch (i)
                {
                    //第一名
                    case 0 :
                    str[map.get(score[i])] = "Gold Medal";
                    break;
                    //第二名
                    case 1 :
                    str[map.get(score[i])] = "Silver Medal";
                    break;
                    //第三名
                    case 2 :
                    str[map.get(score[i])] = "Bronze Medal";
                    break;
                }
            } else {
                str[map.get(score[i])] = i + 1 +"";
            }

        }
        return str;
    }
    public void sort1(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = 1; j < nums.length - i; j++) {
                if(nums[j] > nums[j - 1]) {
                    int temp; 
                    temp = nums[j - 1];
                    nums[j - 1] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值