题目大意:给你一些人的分数,让你输出他们的排名,前三名输出金银铜牌。
Problem:
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:
1 2 3 4 |
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.
Solution 1: Sorting ( + Binary Search)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { vector<string> ans; vector<int> s(nums); std::sort(s.begin(), s.end()); vector<string> medals{"Gold", "Silver", "Bronze"}; for (int i = 0; i < nums.size(); ++i) { int rank = s.end() - std::lower_bound(s.begin(), s.end(), nums[i]); if (rank <= 3) ans.push_back(medals[rank - 1] + " Medal"); else ans.push_back(std::to_string(rank)); } return ans; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua // Running time: 13 ms class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { vector<pair<int, int>> s; for (int i = 0; i < nums.size(); ++i) s.emplace_back(nums[i], i); vector<string> medals{"Gold", "Silver", "Bronze"}; std::sort(s.rbegin(), s.rend()); vector<string> ans(nums.size()); for (int i = 0; i < s.size(); ++i) ans[s[i].second] = i < 3 ? (medals[i] + " Medal") : std::to_string(i + 1); return ans; } }; |