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))
4、相对排名
最新推荐文章于 2022-12-02 20:17:11 发布