LeetCode 题解工作台
相对名次
给你一个长度为 n 的整数数组 score ,其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。 运动员将根据得分 决定名次 ,其中名次第 1 的运动员得分最高,名次第 2 的运动员得分第 2 高,依此类推。运动员的名次决定了他们的获奖情况: 名次第 1 的运动员获金…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们使用一个数组 存储 到 的下标,然后对 进行排序,排序规则为:按照 的值从大到小排序。 然后我们定义一个数组 $\textit{top3} = [\text{Gold Medal}, \text{Silver Medal}, \text{Bronze Medal}]$,遍历 ,对于每个下标 ,如果 小于 ,则 为 ,否则为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个长度为 n 的整数数组 score ,其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。
运动员将根据得分 决定名次 ,其中名次第 1 的运动员得分最高,名次第 2 的运动员得分第 2 高,依此类推。运动员的名次决定了他们的获奖情况:
- 名次第
1的运动员获金牌"Gold Medal"。 - 名次第
2的运动员获银牌"Silver Medal"。 - 名次第
3的运动员获铜牌"Bronze Medal"。 - 从名次第
4到第n的运动员,只能获得他们的名次编号(即,名次第x的运动员获得编号"x")。
使用长度为 n 的数组 answer 返回获奖,其中 answer[i] 是第 i 位运动员的获奖情况。
示例 1:
输入:score = [5,4,3,2,1] 输出:["Gold Medal","Silver Medal","Bronze Medal","4","5"] 解释:名次为 [1st, 2nd, 3rd, 4th, 5th] 。
示例 2:
输入:score = [10,3,8,9,4] 输出:["Gold Medal","5","Bronze Medal","Silver Medal","4"] 解释:名次为 [1st, 5th, 3rd, 2nd, 4th] 。
提示:
n == score.length1 <= n <= 1040 <= score[i] <= 106score中的所有值 互不相同
解题思路
方法一:排序
我们使用一个数组 存储 到 的下标,然后对 进行排序,排序规则为:按照 的值从大到小排序。
然后我们定义一个数组 ,遍历 ,对于每个下标 ,如果 小于 ,则 为 ,否则为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n = len(score)
idx = list(range(n))
idx.sort(key=lambda x: -score[x])
top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"]
ans = [None] * n
for i, j in enumerate(idx):
ans[j] = top3[i] if i < 3 else str(i + 1)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n + m) |
| 空间 | O(m) |
面试官常问的追问
外企场景- question_mark
They want to see whether you preserve original indices after sorting descending scores.
- question_mark
They may ask why unique scores remove tie-handling logic from Relative Ranks.
- question_mark
They are checking whether you notice the output order is input order, not sorted order.
常见陷阱
外企场景- error
Sorting the scores alone and forgetting which athlete each score belonged to.
- error
Writing medal labels in sorted order and returning that sorted array instead of mapping back to original positions.
- error
Using zero-based rank strings like "3" for the fourth athlete instead of converting placement to 1-based rank text.
进阶变体
外企场景- arrow_right_alt
Return only numeric ranks without medal strings, which removes the top-three special-case branch.
- arrow_right_alt
Handle duplicate scores, which changes Relative Ranks into a tie-ranking problem with shared placements.
- arrow_right_alt
Process athletes as they arrive, where a heap becomes more natural than one final sorting pass.