|
33 | 33 | </div> |
34 | 34 |
|
35 | 35 |
|
| 36 | +**Related Topics**: |
| 37 | +[Array](https://leetcode.com/tag/array/), [Greedy](https://leetcode.com/tag/greedy/) |
| 38 | + |
36 | 39 | ## Solution 1. |
37 | 40 |
|
38 | 41 | ```cpp |
|
43 | 46 | class Solution { |
44 | 47 | public: |
45 | 48 | vector<int> advantageCount(vector<int>& A, vector<int>& B) { |
46 | | - sort(A.begin(), A.end()); |
47 | | - vector<int> copy(B.begin(), B.end()); |
48 | | - sort(B.begin(), B.end()); |
49 | | - unordered_map<int, queue<int>> m; |
50 | | - queue<int> leftover; |
51 | | - int i = 0; |
52 | | - for (int a : A) { |
53 | | - if (a > B[i]) m[B[i++]].push(a); |
54 | | - else leftover.push(a); |
| 49 | + int N = A.size(), i = 0; |
| 50 | + vector<int> ia(N), ib(N), ans(N, -1); |
| 51 | + iota(begin(ia), end(ia), 0); |
| 52 | + iota(begin(ib), end(ib), 0); |
| 53 | + sort(begin(ia), end(ia), [&](int a, int b) { return A[a] > A[b]; }); |
| 54 | + sort(begin(ib), end(ib), [&](int a, int b) { return B[a] > B[b]; }); |
| 55 | + for (int j = 0; i < N && j < N; ++i) { |
| 56 | + while (j < N && B[ib[j]] >= A[ia[i]]) ++j; |
| 57 | + if (j < N) { |
| 58 | + ans[ib[j++]] = A[ia[i]]; |
| 59 | + } else break; |
55 | 60 | } |
56 | | - vector<int> ans; |
57 | | - for (int b : copy) { |
58 | | - if (m[b].size()) { |
59 | | - ans.push_back(m[b].front()); |
60 | | - m[b].pop(); |
61 | | - } else { |
62 | | - ans.push_back(leftover.front()); |
63 | | - leftover.pop(); |
| 61 | + for (int j = 0; i < N && j < N; ++i) { |
| 62 | + while (j < N && ans[j] != -1) ++j; |
| 63 | + if (j < N) { |
| 64 | + ans[j++] = A[ia[i]]; |
64 | 65 | } |
65 | 66 | } |
66 | 67 | return ans; |
|
0 commit comments