506. Relative Ranks*
https://leetcode.com/problems/relative-ranks/description/
题目描述
Given scores of N
athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal"
, "Silver Medal"
and "Bronze Medal"
.
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative ranks according to their scores.
Note:
N
is a positive integer and won’t exceed10,000
.- All the scores of athletes are guaranteed to be unique.
解题思路
其实就是求 argmax
.
C++ 实现 1
没啥说的, 排序, 然后将前三设置为 medal
, 注意排序的时候要保留每个运动员的索引. 下面的代码可以多体会. 使用 vector<pair<int, int>>
在保留分数的同时保留索引, 另一方面, 使用 emplace_back
构建对象. 排序时, 使用 scores.rbegin()
等反向迭代器, 使得分数排序可以从大到小(默认是从小到大, 比如使用 nums.begin()
的话)
注意:
- 使用反向迭代器进行从大到小排序.
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
// 保存每个运动员的分数和索引, emplace 使用构造函数构建对象
// 而不是拷贝对象.
vector<pair<int, int>> scores;
vector<string> medals = {"Gold", "Silver", "Bronze"};
for (int i = 0; i < nums.size(); ++i)
scores.emplace_back(nums[i], i);
// 默认从小到大排序, 现在从大到小排序
std::sort(scores.rbegin(), scores.rend());
vector<string> res(nums.size());
for (int i = 0; i < scores.size(); ++i)
res[scores[i].second] = i < 3 ? (medals[i] + " Medal") : to_string(i + 1);
return res;
}
};
C++ 实现 2
C++ 实现 1
是两年前写的, 下面是今天完成的, C++ 的很多特性忘记了, 下面的实现速度较慢…
class Solution {
private:
struct Comp {
Comp(const vector<int> &nums) : score_(nums) {}
bool operator()(int i, int j) {
return score_[i] > score_[j];
}
vector<int> score_;
};
public:
vector<string> findRelativeRanks(vector<int>& nums) {
auto comp = Comp(nums);
int n = nums.size();
vector<int> arr(n);
for (int i = 0; i < n; ++i)
arr[i] = i;
std::sort(arr.begin(), arr.end(), comp);
vector<string> res(n);
for (int i = 0; i < n; ++i) {
if (i == 0) res[arr[i]] = "Gold Medal";
else if (i == 1) res[arr[i]] = "Silver Medal";
else if (i == 2) res[arr[i]] = "Bronze Medal";
else res[arr[i]] = std::to_string(i + 1);
}
return res;
}
};