方法一:大顶堆
这道题看到题目就会想到排序,但是问题是排序之后元素之间的顺序可能会被改变,最后的输出结果要和原始数组中元素的位置是对应的,那就需要将元素的值和下标一起保存起来,再根据元素值进行排序。
class Solution {
public String[] findRelativeRanks(int[] score) {
String[] res = new String[score.length];
// 大顶堆
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] nums1, int[] nums2) {
return nums1[0] != nums2[0] ? nums2[0] - nums1[0] : nums1[0] - nums2[0];
}
});
for (int i = 0; i < score.length; i++) {
pq.offer(new int[]{score[i], i});
}
int i = 1;
while (!pq.isEmpty()) {
if (i == 1) {
res[pq.peek()[1]] = "Gold Medal";
} else if (i == 2) {
res[pq.peek()[1]] = "Silver Medal";
} else if (i == 3) {
res[pq.peek()[1]] = "Bronze Medal";
} else {
res[pq.peek()[1]] = i + "";
}
pq.poll();
i++;
}
return res;
}
}
方法二:使用Arrays.sort()来排序
class Solution {
public String[] findRelativeRanks(int[] score) {
String[] res = new String[score.length];
String[] medals = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};
int[][] arr = new int[score.length][2];
for (int i = 0; i < score.length; i++) {
arr[i][0] = score[i];
arr[i][1] = i;
}
Arrays.sort(arr, (a, b) -> b[0] - a[0]);
for (int i = 0; i < score.length; i++) {
if (i >= 3) {
res[arr[i][1]] = Integer.toString(i + 1);
} else {
res[arr[i][1]] = medals[i];
}
}
return res;
}
}