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                
  • 相关阅读:
    mysql中timestamp自动更新
    Jquery JQZoom Plugin 放大鏡效果 Two
    ASP.NET MVC 之路(一)HtmlHelper 擴展控件
    我的第一个控件
    Visifire Silverlight Chart 比 Silverlight Toolkit Chart 好的兩點
    Jquery Magnify Plugin 放大鏡效果 One
    Asp.Net MVC 之路(二)Html Helper擴展之二
    一个信仰从此在这里开始(仅此篇是非技术)
    HelloWord之WCF文件的猫咪形式
    第一话 Asp.Net MVC 3.0【Hello World!】
  • 原文地址:https://www.cnblogs.com/bonelee/p/8686232.html
Copyright © 2011-2022 走看看