Skip to content

Commit 253bbd9

Browse files
authored
Create relative-sort-array.cpp
1 parent b921943 commit 253bbd9

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

C++/relative-sort-array.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
7+
unordered_map<int, int> lookup;
8+
for (int i = 0; i < arr2.size(); ++i) {
9+
lookup[arr2[i]] = i;
10+
}
11+
sort(arr1.begin(), arr1.end(),
12+
[&lookup, l = arr2.size()](const auto& a, const auto& b) {
13+
int i = lookup.count(a) ? lookup[a] : l + a;
14+
int j = lookup.count(b) ? lookup[b] : l + b;
15+
return i < j;
16+
});
17+
return arr1;
18+
}
19+
};

0 commit comments

Comments
 (0)