leetcode 870

问题

Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i].

Return any permutation of A that maximizes its advantage with respect to B.

Example 1:

1
2
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]

Example 2:

1
2
Input: A = [12,24,8,32], B = [13,25,32,11]
Output: [24,32,8,12]

Note:

  1. 1 <= A.length = B.length <= 10000
  2. 0 <= A[i] <= 10^9
  3. 0 <= B[i] <= 10^9

分析

https://leetcode.com/problems/advantage-shuffle/discuss/149822/JAVA-Greedy-6-lines-with-Explanation

代码

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
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
int n = A.size();
vector<int> ans(n);
sort(A.begin(), A.end());
priority_queue<pair<int,int>> pq;
for (int i = 0; i < n; ++i) {
pq.push({B[i], i});
}

int lo = 0, hi = n-1;
while (pq.size() != 0) {
int value = pq.top().first;
int index = pq.top().second;
pq.pop();
if (A[hi] > value) {
ans[index] = A[hi--];
} else {
ans[index] = A[lo++];
}
}
return ans;
}
};