• leetcode 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.
    class Solution(object):
        def findRelativeRanks(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            # find pos of num in sorted nums        
            # use hashmap to record number pos
            sorted_nums = sorted(nums, reverse=True)
            pos_map = {n:i for i,n in enumerate(sorted_nums)}
            
            def find_pos(n):
                top3 = ("Gold Medal", "Silver Medal", "Bronze Medal")
                if n < 3:
                    return top3[n]
                else:
                    return str(n+1)
                
            return [find_pos(pos_map[n]) for n in nums]
            
    class Solution(object):
        def findRelativeRanks(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            sort = sorted(nums, reverse=True)
            rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] + map(str, range(4, len(nums) + 1))
            return map(dict(zip(sort, rank)).get, nums)        

    no use map solution:

    class Solution(object):
        def findRelativeRanks(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            pos_arr = [(i, n) for i,n in enumerate(nums)]
            pos_arr.sort(key=lambda x: x[1], reverse=True)
            ans = range(0, len(nums))
            top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"] 
            for rank in range(0, len(nums)):
                pos = pos_arr[rank][0]
                if rank < 3:
                    ans[pos] = top3[rank]
                else:
                    ans[pos] = str(rank+1)
            return ans                
  • 相关阅读:
    http的url长度限制
    windows xp unlock 很慢
    C++的vector::push_back()和vector::resize()比较
    手机开发的7种机型列表
    DELPHI中对NT服务型程序的控制单元
    ICON图标下载地址汇总
    Solving the 'cannot find drf file' problem when compiling packages.
    Delphi常用属性和事件
    免费delphi组件收集
    Delphi中关于Canvas.TextOut
  • 原文地址:https://www.cnblogs.com/bonelee/p/8686232.html
Copyright © 2020-2023  润新知