4:相对排名

1、问题描述

根据 N 名运动员的得分,找到获得最高分前 3 名的人,分别获得金牌、银牌和铜牌。N 是正整数,并且不超过 10000。所有运动员的成绩都保证是独一无二的。

2、问题示例

输入 [5, 4, 3, 2, 1],输出 [“金牌”, “银牌”, “铜牌”, “第4名”, “第5名”],前 3 名运动员分数较高,根据得分依次获得金牌、银牌和铜牌。对于后两名运动员,根据分数输出相对名次。

3、代码实现

1)假设分数数组 nums = [ 37, 98, 56, 77 ] ;

2)新建对象 score,以分数作为键,所处下标位置作为值,得到 score = { 37: 0, 98: 1, 56: 2, 77: 3 };

3)对原数组 nums 进行倒序排列,得到 sortedScore = [ 98, 77, 56, 37 ];

4)新建与原数组 nums 长度相等的新数组 result,其值均设为 0 ,result = [ 0, 0, 0, 0 ],用来保存原数组 nums 中每个分数对应的最终名次;

5)循环数组 sortedScore,以其每个元素值 sortedScore[i] 作为 score 对象的键,即 score[sortedScore[i]],

得到的每一个数据便是原数组 nums 中每个分数所在的位置:

score[98] = 1

score[77] = 3

score[56] = 2

score[37] = 0

即 temp = [1, 3, 2, 0],temp 数组便是分数从高到低排列时,每个分数在原数组 nums 的下标位置作为其元素值的数组,

所以 temp = [ 第一名位于1,第二名位于3,第三名位于3,第四名位于0 ]

6)把 temp 数组的元素作为 result 的下标,便得到原数组分数的对应位置的名次,

result [ temp[ i ] ] = “第” + str(i + 1) + “名”

即 result [score[ sortedScore[ i ] ] ] = “第” + str(i + 1) + “名”

result[1] = 金牌

result[3] = 银牌

result[2] = 铜牌

result[0] = 第四名

所以 result = [ ‘第4名’, ‘金牌’, ‘铜牌’, ‘银牌’ ]

class Solution:
    def findRelativeRank(self, nums):
        score = {}
        for i in range(len(nums)):
            score[nums[i]] = i

        sortedScore = sorted(nums, reverse=True)
        result = [0] * len(nums)

        for i in range(len(sortedScore)):
            res = "第" + str(i + 1) + "名"
            if i == 0:
                res = "金牌"
            if i == 1:
                res = "银牌"
            if i == 2:
                res = "铜牌"
            result[score[sortedScore[i]]] = res
        return result


if __name__ == "__main__":
    num = [37, 98, 56, 77]
    print("原分数数组:{}".format(num))

    s = Solution()
    result = s.findRelativeRank(num)
    print("对应名次数组:{}".format(result))
原分数数组:[100, 98, 56, 77, 0]
对应名次数组:['金牌', '银牌', '第4名', '铜牌', '第5名']

另外一种方法

from IPython import embed
class Solution:
    def findRelativeRank(self, nums):
        result = [0] * len(nums)
        for i in range(len(nums)):
            index = nums.index(max(nums))
            nums[index] = -1
            if i == 0:
                result[index] = "金牌"
                continue
            if i == 1:
                result[index] = "银牌"
                continue
            if i == 2:
                result[index] = "铜牌"
                continue
            else:
                result[index] = "第" + str(i + 1) + "名"

        return result



if __name__ == "__main__":
    num = [100, 98, 56, 77, 0,999]
    print("原分数数组:{}".format(num))

    s = Solution()
    result = s.findRelativeRank(num)
    print("对应名次数组:{}".format(result))

原分数数组:[100, 98, 56, 77, 0, 999]
对应名次数组:['银牌', '铜牌', '第5名', '第4名', '第6名', '金牌']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值