1200. 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.
您在真实的面试中是否遇到过这个题?  

样例

N is a positive integer and won't exceed 10,000.

All the scores of athletes are guaranteed to be unique.

这道题我开始做错了,我居然认为数字低才是得分高,也不知道脑子咋想的。

这道题是使用优先队列最为简单,其实是用一个可以自动排序的数据结构比较简单,用map也可以

class Solution {
public:
    /**
     * @param nums: List[int]
     * @return: return List[str]
     */
    vector<string> findRelativeRanks(vector<int> &nums) {
        // write your code here
        int n = nums.size(),;
        int cnt = 1;
        vector<string> res(n, "");
        priority_queue<pair<int, int>> q;
        for (int i = 0; i < n; ++i) {
            q.push({nums[i], i});
        }
        for (int i = 0; i < n; ++i) {
            int idx = q.top().second; 
            q.pop();
            if (cnt == 1) res[idx] = "Gold Medal";
            else if (cnt == 2) res[idx] = "Silver Medal";
            else if (cnt == 3) res[idx] = "Bronze Medal";
            else res[idx] = to_string(cnt);
            ++cnt; 
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80747804