-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRankTransformOfArray.java
More file actions
49 lines (39 loc) · 1.31 KB
/
RankTransformOfArray.java
File metadata and controls
49 lines (39 loc) · 1.31 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package array;
import java.util.*;
/**
* Description: https://leetcode.com/problems/rank-transform-of-an-array
* Difficulty: Easy
* Time complexity: O(nlog n)
* Space complexity: O(n)
*/
public class RankTransformOfArray {
public int[] arrayRankTransformViaSorting(int[] arr) {
int[] copy = Arrays.copyOf(arr, arr.length);
Arrays.sort(copy);
Map<Integer, Integer> rankMap = new HashMap<>();
for (int num : copy) {
// rank is the number of elements, smaller than the current plus one
rankMap.putIfAbsent(num, rankMap.size() + 1);
}
int[] ranks = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
ranks[i] = rankMap.get(arr[i]);
}
return ranks;
}
public int[] arrayRankTransformViaTreeMap(int[] arr) {
Map<Integer, List<Integer>> sortedMapOfIndices = new TreeMap<>();
for (int i = 0; i < arr.length; i++) {
sortedMapOfIndices.computeIfAbsent(arr[i], __ -> new ArrayList<>()).add(i);
}
int rank = 1;
int[] ranks = new int[arr.length];
for (List<Integer> indices : sortedMapOfIndices.values()) {
for (int i : indices) {
ranks[i] = rank;
}
rank++;
}
return ranks;
}
}