0%

relative-ranks

Relative Ranks – LeetCode 506

Problem

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”.iven two binary strings, return their sum (also a binary string).

Note:

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

Example

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.

Answer

Original

Code

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
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
int ma = 0, mi = 0x7fffffff;
for(int &i : nums){
ma = max(ma, i);
mi = min(mi, i);
}
vector<int> map(ma - mi + 1, -1);
for(unsigned i = 0; i != nums.size(); ++i)
map[nums[i] - mi] = i;
const vector<string> s = {"Gold Medal", "Silver Medal", "Bronze Medal"};
vector<string> result(nums.size());
int i = ma - mi, cnt = 0;
for(;i >= 0 && cnt < 3; --i){
if(map[i] != -1)
result[map[i]] = s[cnt++];
}
++cnt;
for(;i >= 0; --i){
if(map[i] != -1)
result[map[i]] = to_string(cnt++);
}
return result;
}
};

思路

得益于题目说明了不会超过10000,于是使用数组打表的方式做。 时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$12$ ms,排名$0.0\%$

Better

思路

还没看到更好的思路。