Skip to content

Commit f705ea1

Browse files
authored
Create advantage-shuffle.cpp
1 parent 64135c1 commit f705ea1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/advantage-shuffle.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
7+
vector<int> sortedA(A.cbegin(), A.cend());
8+
sort(sortedA.begin(), sortedA.end());
9+
vector<int> sortedB(B.cbegin(), B.cend());
10+
sort(sortedB.begin(), sortedB.end());
11+
12+
unordered_map<int, vector<int>> candidates;
13+
vector<int> others;
14+
int j = 0;
15+
for (const auto& a : sortedA) {
16+
if (a > sortedB[j]) {
17+
candidates[sortedB[j]].emplace_back(a);
18+
++j;
19+
} else {
20+
others.emplace_back(a);
21+
}
22+
}
23+
vector<int> result;
24+
for (const auto& b : B) {
25+
if (!candidates[b].empty()) {
26+
result.emplace_back(candidates[b].back());
27+
candidates[b].pop_back();
28+
} else {
29+
result.emplace_back(others.back());
30+
others.pop_back();
31+
}
32+
}
33+
return result;
34+
}
35+
};

0 commit comments

Comments
 (0)