重新排名:相对名次

122 篇文章 2 订阅

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

N 是一个正整数并且不会超过 10000。
所有运动员的成绩都不相同。

# -*- coding: utf-8 -*-
#!/usr/bin/env python

"""
@author: WowlNAN

@github: https://github.com/WowlNAN

@blog: https://blog.csdn.net/qq_21264377

"""
class Solution:
    def findRelativeRanks(self, nums):
        a=sorted(nums, reverse=True)
        b={}
        for i in range(len(a)):
            if i==0:
                b[a[i]]='Gold Medal'
            elif i==1:
                b[a[i]]='Silver Medal'
            elif i==2:
                b[a[i]]='Bronze Medal'
            else:
                b[a[i]]=str(i+1)
        ranks=[]
        for i in range(len(a)):
            ranks.append(b.get(nums[i]))
        return ranks

笔记:
就是排序建立字典,按原记录数组索引,从字典中找出对应名次。
例子:
records = [1, 3, 5, 2, 7]
=> sorted_records = [7, 5, 3, 2, 1]
建立记录 – 名次字典
记录:7, 5, 3, 2, 1
索引:0, 1, 2, 3, 4
排名:1, 2, 3, 4, 5
名次:Gold Medal, Silver Medal, Bronze Medal, 4, 5
字典:dictionary = {7: ‘Gold Medal’, 5: ‘Silver Medal’, 3: ‘Bronze Medal’, 2: ‘4’, 1:‘5’}
比对原记录:
records[0] = 1
=> dictionary[1] = ‘5’
records[1] = 3
=> dictionary[3] = ‘Bronze Medal’
records[2] = 5
=> dictionary[5] = ‘Silver Medal’
records[3] = 2
=> dictionary[2] = ‘4’
records[4] = 7
=> dictionary[7] = ‘Gold Medal’
解:
[ ‘5’, ‘Bronze Medal’, ‘Silver Medal’, ‘4’, ‘Gold Medal’]
至此完成相对排名。


  1. 题目来源:力扣LeetCode ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值