题目链接:
力扣https://leetcode-cn.com/problems/relative-ranks/
【分析】分数是唯一的,所以可以用来当键去映射他在原数组中的位置,对score进行排序后,此时所在的位置即为排名,然后遍历原始数组,因为score现在已经是有序,所以可以直接使用二分查找找出排名,填入原始数组中分数所在的位置。
注意:在使用bisect.bisect(array, i)时,array必须是从小到大进行排序的,不然找不到确切的位置。那么找到这个位置后要根据原始数组的长度进行一个转换。
class Solution:
def findRelativeRanks(self, score):
tab = {1:"Gold Medal",2:"Silver Medal",3:"Bronze Medal"}
from copy import deepcopy
import bisect
l = deepcopy(score)
n, res = len(l), []
l.sort()
for i in score:
idx = bisect.bisect(l, i)
res.append(tab.get(n - idx + 1, n - idx + 1))
return res