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                
  • 相关阅读:
    js面向对象设计之function类
    js 面向对象设计之 Function 普通类
    JS 面试题 实践一
    es6面试问题——Promise
    我给出的一份前端面试题
    如何面试前端工程师?
    前端面试中的自我介绍
    第四章 --- 关于Javascript 设计模式 之 迭代器模式
    第三章 --- 关于Javascript 设计模式 之 代理模式
    第二章 --- 关于Javascript 设计模式 之 策略模式
  • 原文地址:https://www.cnblogs.com/bonelee/p/8686232.html
Copyright © 2011-2022 走看看