publicclassSolution {
publicint[]arrayRankTransform(int[] arr) {
if (arr.length== 0) {
return arr;
}
//Make a copy of array so that we don't loose order of elements in original arrayint[] sortedArr = Arrays.copyOf(arr, arr.length);
// sort the array Arrays.sort(sortedArr);
Map<Integer, Integer> rankMap =new HashMap<>();
int rank = 1;
for (int i = 0; i < sortedArr.length; i++) {
// if map don't contain that element then map it with it's rankif (!rankMap.containsKey(sortedArr[i])) {
rankMap.put(sortedArr[i], rank);
rank++;
}
// otherwise that element rank is already calculated }
// create the result arrayint[] res =newint[arr.length];
// Put the ranks from the map into arrayfor (int i = 0; i < arr.length; i++) {
res[i]= rankMap.get(arr[i]);
}
return res;
}
}
classSolution:
defarrayRankTransform(self, arr: List[int]) -> List[int]:
ifnot arr:
return arr
# Step 1: Sort the array while keeping track of the original indices sorted_arr = sorted(enumerate(arr), key=lambda x: x[1])
# Step 2: Create a rank dictionary rank_dict = {}
rank =1for i, (index, value) in enumerate(sorted_arr):
if value notin rank_dict:
rank_dict[value] = rank
rank +=1# Step 3: Replace elements in original array with their corresponding rank result = [rank_dict[arr[i]] for i in range(len(arr))]
return result