506. Relative Ranks+数组赋值复制

来源:互联网 发布:遇到网络诈骗怎么举报 编辑:程序博客网 时间:2024/06/15 07:45

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};






原创粉丝点击