题目描述:
给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”(“Gold Medal”, “Silver Medal”, “Bronze Medal”)。
(注:分数越高的选手,排名越靠前。)
示例 1:
输入: [5, 4, 3, 2, 1]
输出: [“Gold Medal”, “Silver Medal”, “Bronze Medal”, “4”, “5”]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” (“Gold Medal”, “Silver Medal” and “Bronze Medal”).
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
提示:
N 是一个正整数并且不会超过 10000。
所有运动员的成绩都不相同。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/relative-ranks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
class Solution {
public String[] findRelativeRanks(int[] nums) {
int[] help = Arrays.copyOf(nums, nums.length);
Arrays.sort(help);
HashMap<Integer,String> map = new HashMap<>();
int count = 1;
for (int i = help.length - 1; i >= 0; i--) {
if(count == 1) map.put(help[i],"Gold Medal");
else if(count == 2) map.put(help[i],"Silver Medal");
else if(count == 3) map.put(help[i],"Bronze Medal");
else map.put(help[i],Integer.toString(count));
count++;
}
String[] st = new String[nums.length];
for (int i = 0; i < st.length; i++) {
st[i] = map.get(nums[i]);
}
return st;
}
}
重写Compartor,实现数组降序:
class Solution {
public String[] findRelativeRanks(int[] nums) {
Integer[] help = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
help[i] = nums[i];
}
Comparator<Integer> cmp = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
Arrays.sort(help,cmp);
HashMap<Integer,String> map = new HashMap<>();
for (int i = 0; i < help.length; i++) {
if(i == 0) map.put(help[i],"Gold Medal");
else if(i == 1) map.put(help[i],"Silver Medal");
else if(i == 2) map.put(help[i],"Bronze Medal");
else map.put(help[i],Integer.toString(i+1));
}
String[] st = new String[nums.length];
for (int i = 0; i < st.length; i++) {
st[i] = map.get(nums[i]);
}
return st;
}
}
利用lambda表达式,完成数组降序排列:
class Solution {
public String[] findRelativeRanks(int[] nums) {
Integer[] help = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
help[i] = nums[i];
}
Arrays.sort(help,(o1,o2)->o2-o1);
HashMap<Integer,String> map = new HashMap<>();
for (int i = 0; i < help.length; i++) {
if(i == 0) map.put(help[i],"Gold Medal");
else if(i == 1) map.put(help[i],"Silver Medal");
else if(i == 2) map.put(help[i],"Bronze Medal");
else map.put(help[i],Integer.toString(i+1));
}
String[] st = new String[nums.length];
for (int i = 0; i < st.length; i++) {
st[i] = map.get(nums[i]);
}
return st;
}
}