LeetCode - 每日一题 506. 相对名次

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
    public String[] findRelativeRanks(int[] score) {
        Map<Integer,Integer> hashmap = new HashMap<>();
        String rank[] = new String[score.length];
        int copy[] = new int[score.length];
        int i = 0,b=1;
        for(int s = 0; s<score.length; s++){
            rank[s] = "0";
        }
        for(int w = 0; w<score.length;w++){
            copy[w] = score[w];
        }
        Arrays.sort(copy);
        while(i<score.length){
            hashmap.put(score[i], i);
            i++;
        }

        for(int j = copy.length-1; j>=0; j--){
            if(b ==1){
                rank[hashmap.get(copy[j])] = "Gold Medal";
            }else if(b==2) {
                rank[hashmap.get(copy[j])]= "Silver Medal";
            }else if(b==3) {
                rank[hashmap.get(copy[j])]="Bronze Medal";
            }else
                rank[hashmap.get(copy[j])]=String.valueOf(b);
            b++;
        }
        return rank;
    }
}

执行用时:7 ms, 在所有 Java 提交中击败了67.58%的用户

内存消耗:39.2 MB, 在所有 Java 提交中击败了89.56%的用户

解析如下: 假设有一组数据:score { 5, 4, 3, 2, 1}

        1.  先定义一个空数组rank赋初值为0

        2.  再将score的值赋给copy数组里,在将copy数组排好序,此时copy数组值为{ 1, 2,3, 4, 5}

        3.  在给hashmap赋初值,hashmap的值为{(5,1), (4,2), (3,3), (2,4), (1,5)}

        4.  在循环里,如果b的值等于1, 就将rank[ hashmap.get(copy(4))]  --> rank[ hashmap.get(5)] --> rank[1] = "Gold Medal", 以此类推,返回rank即可。

该答案将排序好的数组利用hashmap找key的方式,将数组rank的值按要求排列起来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值