[LeetCode 870] Advantage Shuffle
程序员文章站
2022-03-31 19:08:42
...
题目
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:
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]
Example 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
思路
题目求解的目标类似田忌赛马,找一个对应位置的数字比B大,并且大的数量最多的排列即可。
采用贪心算法,找A中最大的值A_max
与B中最大的值B_max
比较,如果A_max > B_max
,则找A中次大的值与B中次大的值比较;如果A_max < B_max
,则说明这个位置上A找不到值打过B了,此时找B中次大的值比较即可。
基于上诉思路,则可以分别构造A和B的最大堆heapA
和heapB
来获取A和B中的最大值进行比较。
Code in C++
class Solution {
struct Node {
int index;
int value;
Node(int idx, int val): index(idx), value(val) {}
bool operator<(const Node &b) const { // the last const is a must
return value < b.value;
}
bool operator>(const Node &b) const { // the last const is a must
return value > b.value;
}
};
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
priority_queue<Node> heapA, heapB;
vector<int> result;
vector<int> remain;
int size = A.size();
// for performance
result.resize(size);
remain.reserve(size);
for (size_t i = 0; i < size; ++i) {
heapA.push(Node(i, A[i]));
heapB.push(Node(i, B[i]));
}
while (!heapB.empty()) {
if (heapA.top().value > heapB.top().value) {
result[heapB.top().index] = heapA.top().value;
heapA.pop();
}
else {
remain.push_back(heapB.top().index);
}
heapB.pop();
}
int i = 0;
while (!heapA.empty()) {
result[remain[i++]] = heapA.top().value;
heapA.pop();
}
return result;
}
};
性能
优化方案
- 最后可以通过遍历
heapA
的方式来获取没有被分配的值,减少pop()
的开销。
上一篇: 紧急避孕药吃多了会怎么样