[LeetCode 870] Advantage Shuffle

题目

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的最大堆heapAheapB来获取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()的开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值