链接
题意
给定N个运动员的成绩,输出他们对应的排名。前三名输出格式为:"Gold Medal", "Silver Medal", "Bronze Medal",其他成绩输出名次即可。
思路
- 拷贝一份数组
- 将数组的值和下标最为key和value存入map
- 对其中一数组排序
- 根据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.