|
| 1 | +''' |
| 2 | + Given an array of integers arr, replace each element with its rank. |
| 3 | +
|
| 4 | + The rank represents how large the element is. The rank has the |
| 5 | + following rules: |
| 6 | + - Rank is an integer starting from 1. |
| 7 | + - The larger the element, the larger the rank. If two elements |
| 8 | + are equal, their rank must be the same. |
| 9 | + - Rank should be as small as possible. |
| 10 | +
|
| 11 | + Example: |
| 12 | + Input: arr = [40,10,20,30] |
| 13 | + Output: [4,1,2,3] |
| 14 | + Explanation: 40 is the largest element. 10 is the smallest. 20 is |
| 15 | + the second smallest. 30 is the third smallest. |
| 16 | +
|
| 17 | + Example: |
| 18 | + Input: arr = [100,100,100] |
| 19 | + Output: [1,1,1] |
| 20 | + Explanation: Same elements share the same rank. |
| 21 | +
|
| 22 | + Example: |
| 23 | + Input: arr = [37,12,28,9,100,56,80,5,12] |
| 24 | + Output: [5,3,4,2,8,6,7,1,3] |
| 25 | +
|
| 26 | + Constraints: |
| 27 | + - 0 <= arr.length <= 10^5 |
| 28 | + - -10^9 <= arr[i] <= 10^9 |
| 29 | +''' |
| 30 | +#Difficulty: Easy |
| 31 | +#37 / 37 test cases passed. |
| 32 | +#Runtime: 340 ms |
| 33 | +#emory Usage: 36.2 MB |
| 34 | + |
| 35 | +#Runtime: 340 ms, faster than 66.17% of Python3 online submissions for Rank Transform of an Array. |
| 36 | +#Memory Usage: 36.2 MB, less than 19.18% of Python3 online submissions for Rank Transform of an Array. |
| 37 | + |
| 38 | +class Solution: |
| 39 | + def arrayRankTransform(self, arr: List[int]) -> List[int]: |
| 40 | + nums_indices = {} |
| 41 | + sorted_array = sorted(set(arr)) |
| 42 | + for index, num in enumerate(sorted_array): |
| 43 | + nums_indices[num] = index |
| 44 | + for index, num in enumerate(arr): |
| 45 | + arr[index] = 1 + nums_indices[num] |
| 46 | + return arr |
0 commit comments