题目0506.相对名次
给出 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").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
解题思路,先从大到小排序,再用原score列表和排序过的列表对照,index就是要返回的列表的元素(前三名替换成字符串)。
注意:
1.用append而不是‘+’ 否则多位数或字符串会被拆成多个。
2.注意python中else的用法,for循环里的else表示当循环条件为false跳出循环时,程序会最先执行 else 代码块中的代码。
3.数组的拷贝:直接赋值就是对象引用,如果要不改变原数组做排序,需要切片或copy函数做浅拷贝。
另外,因为先自己写了希尔排序再建立映射关系所以执行很慢...
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
size = len(score)
gap = size // 2
arr = score.copy()
res_list = []
while gap > 0:
for i in range(gap, size):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] < temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap = gap // 2
for i,item in enumerate(arr):
if arr.index(score[i]) == 0:
res_list.append("Gold Medal")
if arr.index(score[i]) == 1:
res_list.append("Silver Medal")
if arr.index(score[i]) == 2:
res_list.append("Bronze Medal")
if arr.index(score[i]) not in [0,1,2]:
res_list.append(str(arr.index(score[i]) +1))
return res_list