Loading

【LBLD】田忌赛马背后的算法决策

田忌赛马背后的算法决策

870. 优势洗牌

class Solution {
public:
    vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size();
        priority_queue<pair<int, int>, vector<pair<int, int>>, function<bool(pair<int, int>, pair<int, int>)>> maxpq([](auto a, auto b){return a.second < b.second;});
        for (int i = 0; i < n; i++) {
            maxpq.emplace(i, nums2[i]);
        }

        sort(nums1.begin(), nums1.end());
        vector<int> res(n);
        int left = 0, right = n-1;
        while (!maxpq.empty()) {
            auto [i, maxval] = maxpq.top();
            maxpq.pop();
            if (maxval < nums1[right]) {
                res[i] = nums1[right];
                right--;
            }
            else {
                res[i] = nums1[left];
                left++;
            }
        }
        return res;
    }
};
posted @ 2023-04-16 15:47  杨谖之  阅读(5)  评论(0编辑  收藏  举报