LeetCode-Python/Java-506. 相对名次

给出 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. 所有运动员的成绩都不相同。

思路:

先用hashmap记录下来分数和原始下标的映射,key是分数, val是原始下标。

然后逆序排序nums,得到按名次排序的数组,再按照题目要求颁发奖牌和利用之前的hashmap记录给出相对排名。

class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        hashmap = dict()
        for i, score in enumerate(nums):
            hashmap[score] = i
        nums = sorted(nums, lambda x: -1*x)
        
        mapping = {0:"Gold Medal", 1:"Silver Medal", 2:"Bronze Medal"} 
        res = [0 for _ in nums]
        for i, score in enumerate(nums):
            if i <= 2: #前三名
                res[hashmap[score]] = mapping[i]
                continue
            
            res[hashmap[score]] = str(i + 1)
            
        return res
class Solution {
    public String[] findRelativeRanks(int[] nums) {
        int n = nums.length;
        int[] nums1 = Arrays.copyOf(nums, n);
        String[] result = new String[n];       
        Arrays.sort(nums1);

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++){
            map.put(nums[i], i);
    }

        
        for (int i = n - 1; i >=0 ; i--){
            if (i == n - 1)
                result[map.get(nums1[i])] = "Gold Medal";
            else if (i == n - 2)
                result[map.get(nums1[i])] = "Silver Medal";
            else if (i == n - 3)
                result[map.get(nums1[i])] = "Bronze Medal";
            else
                result[map.get(nums1[i])] = String.valueOf(n - i);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/89521685