• 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:

    1. N is a positive integer and won't exceed 10,000.
    2. All the scores of athletes are guaranteed to be unique.  
    3.        

    这是我的代码:

    先用sort给所有运动员排序,然后使用map记录他们的分数和名次,最后替换就可以。

    class Solution {
    public:
        vector<string> findRelativeRanks(vector<int>& nums) {
            vector<int> tmp = nums;
            vector<string> ans;
            map<int,string> my_map;
            int n=1;
            sort(tmp.begin(),tmp.end());
            for(int i = tmp.size()-1; i >= 0; i--){
                my_map[tmp[i]] = to_string(n);
                n++;
            }
            my_map[tmp[tmp.size()-1]] = "Gold Medal";
            my_map[tmp[tmp.size()-2]] = "Silver Medal";
            my_map[tmp[tmp.size()-3]] = "Bronze Medal";
            for(auto &num : nums){
                ans.push_back(my_map[num]);
            }
            return ans;
        }
    };

     抄的python代码:

    class Solution(object):
        def findRelativeRanks(self, nums):
            sort = sorted(nums)[::-1] #将nums按从大到小排序
            
            #生成一个从大到小的list  Gold Medal", "Silver Medal", "Bronze Medal",“4”,“5”
            rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] + list(map(str, range(4, len(nums) + 1)))
            
            #返回nums对应的排名
            return map(dict(zip(sort, rank)).get, nums)
            """
            :type nums: List[int]
            :rtype: List[str]
            """
  • 相关阅读:
    图解ArrayList源码
    HashMap相关
    1. 两数之和
    判定字符是否唯一
    反射相关
    自定义注解
    TreeMap相关
    判定是否互为字符重排
    2. 两数相加
    线程基础
  • 原文地址:https://www.cnblogs.com/hutonm/p/6528929.html
Copyright © 2020-2023  润新知