動機
先做這題,再看1632會比較有感覺
Problem
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:
rr- rt
- Rank is an integer starting from 1. rt
- The larger the element, the larger the rank. If two elements are equal, their rank must be the same. rt
- Rank should be as small as possible. r
r
Example 1:
rrrInput: arr = [40,10,20,30]rOutput: [4,1,2,3]rExplanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.rr
Example 2:
rrrInput: arr = [100,100,100]rOutput: [1,1,1]rExplanation: Same elements share the same rank.rrr
Example 3:
rrrInput: arr = [37,12,28,9,100,56,80,5,12]rOutput: [5,3,4,2,8,6,7,1,3]rrr
r
Constraints:
rr- rt
0 <= arr.length <= 105
rt-109 <= arr[i] <= 109
r
Sol
存位置設定成一樣的rank
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
tbl = defaultdict(list)
for (i,n) in enumerate(arr):
tbl[n].append(i)
rank = 1
for k in sorted(tbl.keys()):
for i in tbl[k]:
arr[i] = rank
rank+=1
return arr