ORIGIN

LeetCode 506. Relative Ranks

ACM 1 mins179 words

Problem Description

506. Relative Ranks

Analysis

First we need to sort the scores from biggest to smallest.

And store the score corresponding to the index, soo that given a score we can know the score is at which rank.

Then loop the original scores , for each score we find its corresponding index and change the index into medal name or rank.

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
27
28
29
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
unordered_map<int,int> mp;
vector<int> sorted = score;
vector<string> ans;
sort(sorted.begin(), sorted.end(),greater<int>());
for(int i = 0; i < score.size(); i ++) {
mp[sorted[i]] = i;
}
for(int i = 0; i < score.size(); i ++){
ans.push_back(getRank(mp[score[i]]));
}
return ans;
}
string getRank(int rank) {
switch(rank) {
case 0:
return "Gold Medal";
case 1:
return "Silver Medal";
case 2:
return "Bronze Medal";
default:
return to_string(rank+1);
}
return "";
}
};
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|