Relative Ranks

可以用桶排序,也可以传统排序,哪个快取决于分数的大小了

class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        if not nums:
            return []

        limit = max(nums) + 1
        bucket = [-1] * limit
        for index, num in enumerate(nums):
            bucket[num] = index

        count = 1
        result = [0] * len(nums)
        for i in xrange(limit - 1, -1, -1):
            if bucket[i] != -1:
                if count == 1:
                    result[bucket[i]] = 'Gold Medal'
                elif count == 2:
                    result[bucket[i]] = 'Silver Medal'
                elif count == 3:
                    result[bucket[i]] = 'Bronze Medal'
                else:
                    result[bucket[i]] = `count`
                count += 1

        return result

纯数值排序的方法

class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        n = len(nums)
        tmp = sorted(zip(nums, range(n)), reverse=True)
        result = [0] * n
        for i in xrange(n):
            if i == 0:
                result[tmp[i][1]] = 'Gold Medal'
            elif i == 1:
                result[tmp[i][1]] = 'Silver Medal'
            elif i == 2:
                result[tmp[i][1]] = 'Bronze Medal'
            else:
                result[tmp[i][1]] = `i + 1`
        return result

results matching ""

    No results matching ""