相对名次

🎯 问题描述(来源于LeetCode)

描述
给你一个长度为 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 位运动员的获奖情况。
    说明
  • n == score.length
  • 1 <= n <= 104
  • 0 <= score[i] <= 106
  • score 中的所有值 互不相同

示例

  • 示例 1:
1
2
3
输入:score = [5,4,3,2,1]
输出:["Gold Medal","Silver Medal","Bronze Medal","4","5"]
解释:名次为 [1st, 2nd, 3rd, 4th, 5th] 。
  • 示例 2:
1
2
3
输入:score = [10,3,8,9,4]
输出:["Gold Medal","5","Bronze Medal","Silver Medal","4"]
解释:名次为 [1st, 5th, 3rd, 2nd, 4th] 。

💻 解题思路

思路1:希尔排序

思路1:代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n=len(score)
nums=score.copy()
indices = list(range(n))
gap=n//2
while gap>0:
for i in range(gap,n):
temp=nums[i]
idx = indices[i]
j=i
while j>=gap and nums[j-gap]<temp:
nums[j]=nums[j-gap]
indices[j]=indices[j-gap]
j-=gap
nums[j]=temp
indices[j]=idx
gap//=2
result = [""] * n
for rank, idx in enumerate(indices):
if rank == 0:
result[idx] = "Gold Medal"
elif rank == 1:
result[idx] = "Silver Medal"
elif rank == 2:
result[idx] = "Bronze Medal"
else:
result[idx] = str(rank + 1)
return result

思路1:📊 性能分析

提交结果
  • 运行时间:31ms击败23.85%
  • 内存消耗:18.61MB击败77.56%
复杂度验证
  • 时间复杂度:O(nlog(n))O(nlog(n))
  • 空间复杂度:O(n)O(n)

思考

使用希尔排序后再建立索引与值的关系