相对名次1
给出 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。
所有运动员的成绩都不相同。
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
class Solution:
def findRelativeRanks(self, nums):
a=sorted(nums, reverse=True)
b={}
for i in range(len(a)):
if i==0:
b[a[i]]='Gold Medal'
elif i==1:
b[a[i]]='Silver Medal'
elif i==2:
b[a[i]]='Bronze Medal'
else:
b[a[i]]=str(i+1)
ranks=[]
for i in range(len(a)):
ranks.append(b.get(nums[i]))
return ranks
笔记:
就是排序建立字典,按原记录数组索引,从字典中找出对应名次。
例子:
records = [1, 3, 5, 2, 7]
=> sorted_records = [7, 5, 3, 2, 1]
建立记录 – 名次字典:
记录:7, 5, 3, 2, 1
索引:0, 1, 2, 3, 4
排名:1, 2, 3, 4, 5
名次:Gold Medal, Silver Medal, Bronze Medal, 4, 5
字典:dictionary = {7: ‘Gold Medal’, 5: ‘Silver Medal’, 3: ‘Bronze Medal’, 2: ‘4’, 1:‘5’}
比对原记录:
records[0] = 1
=> dictionary[1] = ‘5’
records[1] = 3
=> dictionary[3] = ‘Bronze Medal’
records[2] = 5
=> dictionary[5] = ‘Silver Medal’
records[3] = 2
=> dictionary[2] = ‘4’
records[4] = 7
=> dictionary[7] = ‘Gold Medal’
解:
[ ‘5’, ‘Bronze Medal’, ‘Silver Medal’, ‘4’, ‘Gold Medal’]
至此完成相对排名。
题目来源:力扣LeetCode ↩︎