• 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]
            """
  • 相关阅读:
    Android Listview 隐藏滚动条
    打开Activity时,不自动显示(弹出)虚拟键盘
    Spring Boot web API接口设计之token、timestamp、sign
    WPF ListView点击删除某一行并获取绑定数据
    WPF中控件的显示与隐藏
    WPF 格式化输出- IValueConverter接口的使用 datagrid列中的值转换显示
    WPF之DataGrid应用 翻页
    WPF中修改DataGrid单元格值并保存
    DataGrid获取单元格的值
    WPF DataGrid 列宽填充表格方法
  • 原文地址:https://www.cnblogs.com/hutonm/p/6528929.html
Copyright © 2020-2023  润新知