File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments