zoukankan      html  css  js  c++  java
  • 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                
  • 相关阅读:
    Android学习笔记(四十):Preference的使用
    怎样在小方框上打对号 小方框内打对勾 word 方框打对勾
    PreTranslateMessage作用和用法
    MyBatis与Spring设置callSettersOnNulls
    EJB3.0开发环境的搭建
    经常使用虚拟现实仿真软件总汇(zz)
    slf自己主动绑定实现类过程推断
    DLNA介绍(包含UPnP,2011/6/20 更新)
    从技术到管理的问题
    NOI第一天感想&小结
  • 原文地址:https://www.cnblogs.com/bonelee/p/8686232.html
Copyright © 2011-2022 走看看