leetcode 1122 - Relative Sort Array

https://leetcode.com/problems/relative-sort-array/

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
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
unordered_set<int> set;
unordered_map<int, int> map;

for (int n : arr2)
set.insert(n);

int len = arr1.size();
int j = len - 1;

for (int i = len - 1; i >= 0; i--) {
int n = arr1[i];

if (set.count(n) == 0)
arr1[j--] = n;
else {
map[n]++;
}
}

int i = 0;
for (int n : arr2) {
int count = map[n];

while (count-- > 0)
arr1[i++] = n;
}

sort(arr1.begin() + i, arr1.end());

return arr1;
}
};