import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
public String[] findRelativeRanks(int[] score) {
Map<Integer,Integer> hashmap = new HashMap<>();
String rank[] = new String[score.length];
int copy[] = new int[score.length];
int i = 0,b=1;
for(int s = 0; s<score.length; s++){
rank[s] = "0";
}
for(int w = 0; w<score.length;w++){
copy[w] = score[w];
}
Arrays.sort(copy);
while(i<score.length){
hashmap.put(score[i], i);
i++;
}
for(int j = copy.length-1; j>=0; j--){
if(b ==1){
rank[hashmap.get(copy[j])] = "Gold Medal";
}else if(b==2) {
rank[hashmap.get(copy[j])]= "Silver Medal";
}else if(b==3) {
rank[hashmap.get(copy[j])]="Bronze Medal";
}else
rank[hashmap.get(copy[j])]=String.valueOf(b);
b++;
}
return rank;
}
}
执行用时:7 ms, 在所有 Java 提交中击败了67.58%的用户
内存消耗:39.2 MB, 在所有 Java 提交中击败了89.56%的用户
解析如下: 假设有一组数据:score { 5, 4, 3, 2, 1}
1. 先定义一个空数组rank赋初值为0
2. 再将score的值赋给copy数组里,在将copy数组排好序,此时copy数组值为{ 1, 2,3, 4, 5}
3. 在给hashmap赋初值,hashmap的值为{(5,1), (4,2), (3,3), (2,4), (1,5)}
4. 在循环里,如果b的值等于1, 就将rank[ hashmap.get(copy(4))] --> rank[ hashmap.get(5)] --> rank[1] = "Gold Medal", 以此类推,返回rank即可。
该答案将排序好的数组利用hashmap找key的方式,将数组rank的值按要求排列起来。