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)