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]
            """
  • 相关阅读:
    7.4 List集合
    vue学习笔记
    javaWEB中web.xml配置文件相关
    maven常用dos命令
    Oracle,sqlserver,mySQl的区别和联系:
    oracle数据库视图,序列,索引的sql语句查看
    java 异常处理
    线程专题
    package、folder和source folder的区别
    Java内存分配之堆、栈和常量池
  • 原文地址:https://www.cnblogs.com/hutonm/p/6528929.html
Copyright © 2011-2022 走看看