LeetCode506 Relative Ranks

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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”.

Note:

  1. N is a positive integer and won’t exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.

样例

1
2
3
4
5
6
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.

思路

根据数组元素的大小,给出排名。前三输出金银铜牌,其余输出名次。

sort一下就好了,用pair姿势会比较优雅。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
vector<pair<int, int> > vec;
// pair第一位存元素大小,第二位存下标
int siz = nums.size(), id = 0;
for (int& x: nums) vec.push_back(make_pair(-x, id++));
sort(vec.begin(), vec.end());
vector<string> ans(siz);
string medals[3] = {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < siz; ++i) {
id = vec[i].second;
if (i < 3) ans[id] = medals[i];
else ans[id] = to_string(i + 1);
}
return ans;
}
};
分享到 评论