题目
解题思路
注意问题:
- 给定的sorce数组不是排好序的,不能直接根据数组顺序进行名次的分配。
- 前三名又额外的荣誉称号,要单独列出来。
主要思路: - 设置一个
Map
,使用Map将数组中的数据存储起来,将成绩作为Key
,将索引作为Value
进行存储。 - 因为Arrays中的sort函数只能从小到大排序,所以稍微改了一下冒泡,使数组从大到小排列。
- 遍历数组,使用
switch
进行前三名荣誉的判别。遍历的时候将排序后数组的值作为Map
的get()
的参数找到该成绩在原数组的位置。 - 创建一个String类型的数组,根据上面
get()
查询到的真正索引位置,将相关的荣誉加入到String数组中,完成任务。。。
代码
class Solution {
public String[] findRelativeRanks(int[] score) {
String[] str = new String[score.length];
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < score.length; i++) {
//成绩作为key,索引作为value
map.put(score[i], i);
}
sort1(score);
// for (int i : score) {
// System.out.print(i + " ");
// }
for (int i = 0; i < score.length; i++) {
if (i < 3) {
switch (i)
{
//第一名
case 0 :
str[map.get(score[i])] = "Gold Medal";
break;
//第二名
case 1 :
str[map.get(score[i])] = "Silver Medal";
break;
//第三名
case 2 :
str[map.get(score[i])] = "Bronze Medal";
break;
}
} else {
str[map.get(score[i])] = i + 1 +"";
}
}
return str;
}
public void sort1(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 1; j < nums.length - i; j++) {
if(nums[j] > nums[j - 1]) {
int temp;
temp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = temp;
}
}
}
}
}