leetcode 506. Relative Ranks
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 exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
关联值 和 下标 然后排序,最后在对应到原来的序列
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { vector<pair<int, int> > v; for (int i = 0; i < nums.size(); ++i) { pair<int, int> p; p.first = nums[i]; p.second = i; v.push_back(p); } sort(v.begin(), v.end()); vector<string> s; map<int, int> mp; for (int i = v.size() - 1; i >= 0; --i) { mp[v[i].second] = v.size() - i; } for (int i = 0; i < nums.size(); ++i) { int x = mp[i]; if (x == 1) s.push_back("Gold Medal"); else if (x == 2) s.push_back("Silver Medal"); else if (x == 3) s.push_back("Bronze Medal"); else s.push_back(to_string(x)); } return s; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: