leetcode_506 相对名次

155 阅读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").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。

核心代码

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        hashmap = dict()
        for i,_score in enumerate(score):
            hashmap[_score] = i
        score = sorted(score,key = lambda x: -1 * x)
        mapping = {0:"Gold Medal",1:"Silver Medal",2:"Bronze Medal"}

        res = [0 for _ in score]

        for i,_score in enumerate(score):
            if i <= 2:
                res[hashmap[_score]] = mapping[i]
                continue
            res[hashmap[_score]] = str(i + 1)
        return res

image.png

解题思路:我们构建一个字典,字典中分数做键,下标做值,我们在对分数列表进行逆序排名,我们对排序后的列表进行指定是从mapping中获取标签名称还是相对数字名次,相对比较简单。