Leetcode 506(Java)

来源:互联网 发布:linux locale命令 编辑:程序博客网 时间:2024/05/18 17:04

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:
N is a positive integer and won’t exceed 10,000.
All the scores of athletes are guaranteed to be unique.

AC码:

public class Solution {    public String[] findRelativeRanks(int[] nums) {        Integer[] num = new Integer[nums.length];        for(int i=0;i<nums.length;i++){            num[i] = nums[i];        }                Comparator<Integer> compr = new Comparator<Integer>(){            public int compare(Integer m,Integer n){                return n.compareTo(m);            }        };        Arrays.sort(num, compr);        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();        int n=1;        for(int x:num){            map.put(x, n);            n++;        }        String[] result = new String[nums.length];        int index = 0;        for(int y:nums){            switch (map.get(y)){            case 1:                result[index] = "Gold Medal";                break;            case 2:                result[index] = "Silver Medal";                break;            case 3:                result[index] = "Bronze Medal";                break;            default:                result[index] = Integer.toString(map.get(y));                break;            }            index++;        }        return result;    }}
0 0
原创粉丝点击