-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.java
29 lines (23 loc) · 849 Bytes
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.*;
class Solution {
public int[] arrayRankTransform(int[] arr) {
if (arr.length == 0) return new int[0];
// Step 1: Create a sorted copy of the array
int[] sortedArr = arr.clone();
Arrays.sort(sortedArr);
// Step 2: Create a map to store the rank of each element
Map<Integer, Integer> rankMap = new HashMap<>();
int rank = 1;
// Step 3: Assign ranks to sorted elements
for (int num : sortedArr) {
if (!rankMap.containsKey(num)) {
rankMap.put(num, rank++);
}
}
// Step 4: Replace each element in the original array with its rank
for (int i = 0; i < arr.length; i++) {
arr[i] = rankMap.get(arr[i]);
}
return arr;
}
}