zoukankan      html  css  js  c++  java
  • 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]
            """
  • 相关阅读:
    【leetcode】416. Partition Equal Subset Sum
    【leetcode】893. Groups of Special-Equivalent Strings
    【leetcode】892. Surface Area of 3D Shapes
    【leetcode】883. Projection Area of 3D Shapes
    【leetcode】140. Word Break II
    【leetcode】126. Word Ladder II
    【leetcode】44. Wildcard Matching
    【leetcode】336. Palindrome Pairs
    【leetcode】354. Russian Doll Envelopes
    2017.12.22 英语面试手记
  • 原文地址:https://www.cnblogs.com/hutonm/p/6528929.html
Copyright © 2011-2022 走看看