506. Relative Ranks+数组赋值复制

运动员排名与奖牌算法
本文介绍了一种算法,用于确定N位运动员的相对排名,并为前三名分配金、银、铜奖牌。该算法首先复制原始分数数组,然后通过排序和映射来确定每个运动员的最终排名。

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example 1:

Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 
For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.
public class Solution {
    public String[] findRelativeRanks(int[] nums) {
        Map<Integer,Integer> m=new HashMap<>();
        int[] label=new int[nums.length];
        System.arraycopy(nums, 0, label, 0, nums.length);//数组复制,要复制目标,复制起始位置,复制存放数组,存放起始位置,复制长度
        String[] result=new String[nums.length];
        Arrays.sort(label);
        for(int i=0;i<label.length;i++){
            m.put(label[i],label.length-i);
        }
        for(int i=0;i<nums.length;i++){
            Integer x=m.get(nums[i]);
            if(x==1)result[i]="Gold Medal";
            else if(x==2)result[i]="Silver Medal";
            else if(x==3)result[i]="Bronze Medal";
            else result[i]=""+x;
        }
        return result;
    }
}
难点在于创建新数组排序

大神解法:不纠结于数组排序,使用map容器提前记录数组顺序

public String[] findRelativeRanks(int[] nums) {
        Map<Integer, String> map = new LinkedHashMap<>();
        String[] rank = new String[nums.length];
        int index = 4;
        for(int i: nums) map.put(i, "");
        Arrays.sort(nums);
        for(int i = nums.length - 1; i >= 0; i--){
            if(i == nums.length - 1) map.put(nums[i], "Gold Medal");
            if(i == nums.length - 2) map.put(nums[i], "Silver Medal");
            if(i == nums.length - 3) map.put(nums[i], "Bronze Medal");
            if(i < nums.length - 3) map.put(nums[i], String.valueOf(index++));
        }
        int indexOfRank = 0;
        for(String j: map.values()){
            rank[indexOfRank++] = j;
        }
        return rank;
    }

数组当中完全新建一个数组复制而不是引用有两种方法(引用就简单啦,label=nums就可以了):

1. 你可以直接赋值一个个的,会安全的,因为java数组是有界的
2. 你可以使用System.arrayCopy这个效率会高些。

System.arraycopy可以实现自己到自己复制,比如:
int[] a={0,1,2,3,4,5,6}; 
System.arraycopy(a,0,a,3,3);
则结果为:{0,1,2,0,1,2,6};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值