给出 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。
- 所有运动员的成绩都不相同。
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n = len(score)
idx = list(range(n))
idx.sort(key=lambda x: -score[x])
top3 = ['Gold Medal', 'Silver Medal', 'Bronze Medal']
ans = [None] * n
for i in range(n):
ans[idx[i]] = top3[i] if i < 3 else str(i + 1)
return ans
class Solution {
public String[] findRelativeRanks(int[] score) {
int n = score.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; ++i) {
idx[i] = i;
}
Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]);
String[] ans = new String[n];
String[] top3 = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < n; ++i) {
ans[idx[i]] = i < 3 ? top3[i] : String.valueOf(i + 1);
}
return ans;
}
}
class Solution {
public:
vector<string> findRelativeRanks(vector<int> &score) {
int n = score.size();
vector<pair<int, int>> idx;
for (int i = 0; i < n; ++i)
idx.push_back(make_pair(score[i], i));
sort(idx.begin(), idx.end(),
[&](const pair<int, int> &x, const pair<int, int> &y)
{ return x.first > y.first; });
vector<string> ans(n);
vector<string> top3 = {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < n; ++i)
ans[idx[i].second] = i < 3 ? top3[i] : to_string(i + 1);
return ans;
}
};
func findRelativeRanks(score []int) []string {
n := len(score)
idx := make([][]int, n)
for i := 0; i < n; i++ {
idx[i] = []int{score[i], i}
}
sort.Slice(idx, func(i1, i2 int) bool {
return idx[i1][0] > idx[i2][0]
})
ans := make([]string, n)
top3 := []string{"Gold Medal", "Silver Medal", "Bronze Medal"}
for i := 0; i < n; i++ {
if i < 3 {
ans[idx[i][1]] = top3[i]
} else {
ans[idx[i][1]] = strconv.Itoa(i + 1)
}
}
return ans
}