leetcode 506. Relative Ranks

本文提供了一种解决方案来确定运动员的相对名次及前三名的奖牌分配。通过将分数从高到低排序并使用字典映射来高效地找出每个分数对应的名次。
leetcode 506. Relative Ranks

#coding=utf-8
'''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:
N is a positive integer and won't exceed 10,000.
All the scores of athletes are guaranteed to be unique.'''

#根据给定的分数,求相对排名,并分配金银铜奖牌,剩下的标记相对排名

class Solution():
    '''复杂度太高,时间上通不过'''
    def findRelativeRanks(self,nums):
        mid=sorted(nums)[::-1]#先从小到大,在逆序
        medal=["Gold Medal", "Silver Medal", "Bronze Medal"]
        rnums=medal+[str(i) for i in range(4,len(nums)+1)]
        for x in nums:
            nums[nums.index(x)]=rnums[mid.index(x)]

        return nums

    def findRelativeRanks1(self, nums):
        mid = sorted(nums)[::-1]  # 先从小到大,在逆序
        medal = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        rnums = medal + [str(i) for i in range(4, len(nums) + 1)]
        return map(dict(zip(mid,rnums)).get,nums)

        #dict可以将元祖的列表变为字典,dict.get()函数可以取键的值,是一个函数

s=Solution()
nums=[3,9,7,5,1,0,6]
print s.findRelativeRanks(nums)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值