1331. Rank Transform of an Array

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

  • Rank is an integer starting from 1.
  • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
  • Rank should be as small as possible.

给出数组排序后对应的排名,相同的元素相同的排名,但是不会占用下一个名额,也就是说[4, 3, 3, 3]->排名是[2, 1 ,1 ,1]

排序然后开一个字典记录一下当前数的排序就行

class Solution(object):
    def arrayRankTransform(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        d = {}
        ans = []
        for value in sorted(arr):
            d.setdefault(value, len(d) + 1)
        for value in arr:
            ans.append(d[value])
        return ans

 

posted @ 2020-07-02 09:53  whatyouthink  阅读(91)  评论(0编辑  收藏  举报