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 ""; } };
|
Author: o_oyao
License: All articles in this blog are licensed under
CC BY-NC-SA 4.0 unless stating additionally.