题目描述
给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”(“Gold Medal”, “Silver Medal”, “Bronze Medal”)。
(注:分数越高的选手,排名越靠前。)
示例 1:
输入: [5, 4, 3, 2, 1]
输出: [“Gold Medal”, “Silver Medal”, “Bronze Medal”, “4”, “5”]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” (“Gold Medal”, “Silver Medal” and “Bronze Medal”).
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
提示:
N 是一个正整数并且不会超过 10000。
所有运动员的成绩都不相同。
思路分析
- 用temp记录排序好的列表,用dic记录排序好的key,value为对应的名次奖牌
- 对于 0 - 2 的索引,将奖牌字符串作为value值
- 对于 3 - n 的索引,n的索引加 1 就是名次
- res 为需要返回的结果,按遍历 nums 中的元素,返回 dic 的 value
代码示例
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
temp = nums[:]
temp.sort(reverse = True)
dic = {}
lens = len(nums)
dic[temp[0]] = 'Gold Medal'
if lens > 1:
dic[temp[1]] = 'Silver Medal'
if lens > 2:
dic[temp[2]] = 'Bronze Medal'
for n in range(3,lens):
dic[temp[n]] = str(1 + n)
res = [dic[n] for n in nums]
return res