870. Advantage Shuffle

870. Advantage Shuffle

思路
用priority_queue>解决。使用贪心算法,按数组A从大到小尽可能在数组B中找到匹配的元素即可。就像是“田忌赛马”一样,让A的上等马去应付B的中等马,依次类推,就能有尽可能多的匹配对数。
技巧度:C, 思维绕脑度:C
贪心算法

代码

typedef pair mp;

bool operator <(mp &p1, mp &p2){
    return p1.first >= p2.first;
}
class Solution {
public:
    vector advantageCount(vector& A, vector& B) {
        priority_queue q;
        vector res(A.size(), 0);
        stack st;
        map ma;
        map mb;
        
        sort(A.begin(), A.end(), greater());
        
        for (int i = 0; i < B.size(); i++)
            q.push({B[i], i});
        
        for (int i = 0; i < A.size(); i++) {
            while(!q.empty() && A[i] <= q.top().first) {
                st.push(q.top());
                q.pop();
            }
            
            if (!q.empty()) {
                auto p = q.top();
                res[p.second] = A[i];
                q.pop();
            }
            else {
                auto p = st.top();
                res[p.second] = A[i];
                st.pop();
            }
        }
        
        
        return res;
    }
};

你可能感兴趣的:(870. Advantage Shuffle)