-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRelativeSortArray.java
More file actions
43 lines (34 loc) · 1020 Bytes
/
RelativeSortArray.java
File metadata and controls
43 lines (34 loc) · 1020 Bytes
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
package array;
/**
* Description: https://leetcode.com/problems/relative-sort-array
* Difficulty: Easy
* Time complexity: O(m + n)
* Space complexity: O(n)
*/
public class RelativeSortArray {
private static final int MAX_POSSIBLE_VAL = 1000;
public int[] relativeSortArray(int[] arr1, int[] arr2) {
int[] freqMap = buildFreqMap(arr1);
int[] sorted = new int[arr1.length];
int pointer = 0;
for (int num : arr2) {
for (int i = 0; i < freqMap[num]; i++) {
sorted[pointer++] = num;
}
freqMap[num] = 0;
}
for (int num = 0; num <= MAX_POSSIBLE_VAL; num++) {
for (int i = 0; i < freqMap[num]; i++) {
sorted[pointer++] = num;
}
}
return sorted;
}
private int[] buildFreqMap(int[] arr) {
int[] freqMap = new int[MAX_POSSIBLE_VAL + 1];
for (int num : arr) {
freqMap[num]++;
}
return freqMap;
}
}