LeetCode - 506. Relative Ranks

链接

506. Relative Ranks

题意

给定N个运动员的成绩,输出他们对应的排名。前三名输出格式为:"Gold Medal", "Silver Medal", "Bronze Medal",其他成绩输出名次即可。

思路

  1. 拷贝一份数组
  2. 将数组的值和下标最为key和value存入map
  3. 对其中一数组排序
  4. 根据map获得原数组该元素下标,设值即可

代码

Java :

public class Solution {
    public String[] findRelativeRanks(int[] nums) {
        String[] copy = new String[nums.length];
        Map<Integer, Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        Arrays.sort(nums);
        int j = 0;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i >= nums.length - 3) {
                String[] metal = {"Gold Medal", "Silver Medal", "Bronze Medal"};
                copy[map.get(nums[i])] = metal[j++];
            } else {
                copy[map.get(nums[i])] = String.valueOf(nums.length - i);
            }
        }
        return copy;
    }
}

效率

Your runtime beats 74.97 % of java submissions.

posted @ 2017-04-27 13:16  zyoung  阅读(144)  评论(0编辑  收藏  举报