LeetCode506-相对名次

题目链接

英文链接:https://leetcode.com/problems/relative-ranks/

中文链接:https://leetcode-cn.com/problems/relative-ranks/

题目详述

给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”(”Gold Medal”, “Silver Medal”, “Bronze Medal”)。

(注:分数越高的选手,排名越靠前。)

示例 1:

1
2
3
4
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。

提示:

  • N 是一个正整数并且不会超过 10000。
  • 所有运动员的成绩都不相同。

题目详解

  • 对数组按照从大到小排序。
  • 为了不丢失下标信息,需要创建一个数组来保存下标信息,将元素与下标捆绑在一起。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class LeetCode_00506 {

public String[] findRelativeRanks(int[] nums) {
int n = nums.length;
int[][] arr = new int[n][2];
for (int i = 0; i < n; ++i) {
arr[i][0] = nums[i];
arr[i][1] = i;
}
Arrays.sort(arr, (o1, o2) -> Integer.compare(o2[0], o1[0]));
String[] res = new String[n];
int rank = 0;
for (int[] x : arr) {
++rank;
if (rank == 1) {
res[x[1]] = "Gold Medal";
} else if (rank == 2) {
res[x[1]] = "Silver Medal";
} else if (rank == 3) {
res[x[1]] = "Bronze Medal";
} else {
res[x[1]] = String.valueOf(rank);
}
}
return res;
}
}
  • 实际上可以直接创建一个一维数组代表下标,在排序的时候用下标对应元素进行比较。
  • 为了能够自定义 Comparator,需要使用包装类 Integer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class LeetCode_00506 {

public String[] findRelativeRanks(int[] nums) {
int n = nums.length;
Integer[] index = new Integer[n];
for (int i = 0; i < n; ++i) {
index[i] = i;
}
Arrays.sort(index, (o1, o2) -> Integer.compare(nums[o2], nums[o1]));
String[] res = new String[n];
for (int i = 0; i < n; ++i) {
if (i == 0) {
res[index[i]] = "Gold Medal";
} else if (i == 1) {
res[index[i]] = "Silver Medal";
} else if (i == 2) {
res[index[i]] = "Bronze Medal";
} else {
res[index[i]] = String.valueOf(i + 1);
}
}
return res;
}
}