• 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                
  • 相关阅读:
    JavaScript(第五天)【流程控制语句】
    JavaScript(第四天)【运算符】
    JavaScript(第二天)【语法,变量】
    JavaScript(第一天)【<script>标签浅析】
    JavaScript(简介)【Javascript历史】
    [LeetCode-JAVA] Substring with Concatenation of All Words
    [LeetCode-JAVA] Reverse Nodes in k-Group
    [LeetCode-JAVA] Median of Two Sorted Arrays
    [LeetCode-JAVA] Contains Duplicate IIIMaximal Square
    [LeetCode-JAVA] Contains Duplicate III
  • 原文地址:https://www.cnblogs.com/bonelee/p/8686232.html
Copyright © 2020-2023  润新知