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                
复制代码

 

posted @   bonelee  阅读(169)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-04-01 信息检索导论的课件——http://home.ustc.edu.cn/~zhufengx/ir/pdf/
2017-04-01 通过Mesos、Docker和Go,使用300行代码创建一个分布式系统
2017-04-01 varint算法——本质上是牺牲最高位作为标识数据结束位,达到变长编码,说白了就是贪心的分割位
点击右上角即可分享
微信分享提示