-
Notifications
You must be signed in to change notification settings - Fork 0
/
Relative_Sort_Array.java
39 lines (34 loc) · 1.41 KB
/
Relative_Sort_Array.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
30
31
32
33
34
35
36
37
38
39
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
// Create a map to store the frequency of elements in arr1
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : arr1) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
// Create a list to store the sorted elements
List<Integer> sortedList = new ArrayList<>();
// Add the elements from arr2 in the order specified
for (int num : arr2) {
int frequency = frequencyMap.getOrDefault(num, 0);
for (int i = 0; i < frequency; i++) {
sortedList.add(num);
}
frequencyMap.remove(num);
}
// Add the remaining elements from arr1 in ascending order
List<Integer> remainingList = new ArrayList<>(frequencyMap.keySet());
Collections.sort(remainingList);
for (int num : remainingList) {
int frequency = frequencyMap.get(num);
for (int i = 0; i < frequency; i++) {
sortedList.add(num);
}
}
// Convert the list to an array
int[] sortedArray = new int[sortedList.size()];
for (int i = 0; i < sortedList.size(); i++) {
sortedArray[i] = sortedList.get(i);
}
return sortedArray;
}
}