Rank Transform of an Array
To solve this problem, follow these steps:
- First, make a copy of the array and sort it.
- Create a dictionary to keep track of the rank of each number. Initialize the rank to 1.
- Iterate over the sorted array. If the number is not in the dictionary, add it and its rank to the dictionary and increment the rank.
- Finally, replace each element in the original array with its rank from the dictionary.
Here’s the code:
|
|
In this code, sorted(set(arr))
creates a sorted list of unique elements in arr
. {v: i + 1 for i, v in enumerate(sorted_arr)}
maps each number to its rank. And [rank_dict[i] for i in arr]
replaces each number in arr
with its rank.