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]
            """
  • 相关阅读:
    腾讯云 Centos 配置 JDK & Tomcat & Mysql
    JNI编程新手入门:Java和C++的超简单交互
    关于正则表达式的一些实际应用
    CAJ 转化为PDF
    Latex 大括号后多行输出
    Latex 安装
    Neo4j使用操作
    pip 升级操作
    venue recommendation —— 应用场景/用户分类
    Recbole安装及使用
  • 原文地址:https://www.cnblogs.com/hutonm/p/6528929.html
Copyright © 2011-2022 走看看