

可以使用 Python 的 sorted() 方法对 score 进行排序,并使用 dict 记录每个分数对应的排名。然后遍历 score 生成最终的 answer 数组。以下是代码实现:
def findRelativeRanks(score):
# 按得分排序,记录每个分数对应的排名
sorted_score = sorted(score, reverse=True)
rank_dict = {score: str(i + 1) for i, score in enumerate(sorted_score)}
# 特殊处理前三名
medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
for i in range(min(3, len(sorted_score))):
rank_dict[sorted_score[i]] = medals[i]
# 生成最终的获奖结果
return [rank_dict[s] for s in score]
# 示例测试
score = [5, 3, 8, 6, 2]
print(findRelativeRanks(score))
解释:
- 排序:将
score按降序排列,获得从高到低的排名顺序。 - 建立排名映射:使用
dict存储分数到排名的映射。 - 处理前三名:将前三名替换为金牌、银牌和铜牌。
- 生成结果:遍历原始
score,从rank_dict获取对应的排名或奖牌。
示例:
输入:
score = [5, 3, 8, 6, 2]
输出:
['Silver Medal', '4', 'Gold Medal', 'Bronze Medal', '5']
这样就能正确返回所有运动员的获奖情况! 🚀
Python解决LeetCode 506相对名次问题
249

被折叠的 条评论
为什么被折叠?



