zoukankan      html  css  js  c++  java
  • 算法42-----相对名次

    一、题目:

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

    提示:

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

    二、思路:

    复制一个相同数组ans ,排序,定义一个排名数组,从原数组中寻找与arr[j]相同元素,在排名数组中对应位置赋值为j+1(记录运动员排名), j=0,1,2时特殊处理为”Gold Medal”, “Silver Medal”, “Bronze Medal”

    三、代码:

    class Solution(object):
        def findRelativeRanks(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
    
            if len(nums) == 1:
                return ["Gold Medal"]
            elif len(nums) == 2:
                if nums[0] > nums[1]:
                    return ["Gold Medal", "Silver Medal"]
                else:
                    return ["Silver Medal","Gold Medal"]
            ans , d = [0] * len(nums) , sorted([(num,index) for index,num in enumerate(nums)],reverse = True)
            ans[d[0][1]] , ans[d[1][1]] ,ans[d[2][1]] = ["Gold Medal","Silver Medal","Bronze Medal"]
    
            for i in range(3,len(nums)):
                ans[d[i][1]] = str(i+1)
            return ans
            
                
                
            
  • 相关阅读:
    HDU 3537
    POJ 1175
    POJ 1021 人品题
    POJ 2068
    POJ 2608
    POJ 2960
    poj 1635
    ustc 1117
    ural 1468
    数字游戏
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/9935953.html
Copyright © 2011-2022 走看看