priority_queue 自定义 comparator priority_queue 自定义 comparator

LeetCode 373. Find K Pairs with Smallest Sums

本文重点记录需要自定义 comparator 时的priority_queue 的写法。

题目描述

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

Example 1:

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:

Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [[1,1],[1,1]]
Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

Example 3:

Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [[1,3],[2,3]]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]

Constraints:

  • 1 <= nums1.length, nums2.length <= 104
  • -109 <= nums1[i], nums2[i] <= 109
  • nums1 and nums2 both are sorted in ascending order.
  • 1 <= k <= 1000

解题思路

题目的意思是说给出两个有序数组,每次可以从两个数组中各取出一个组成一各二元组,现在要找出前k个二元组,使得这些二元组各自的两个元素之和是最小的。
找出全部 m * n 个二元组的开销是 O(mn),是不必要的。我们注意到两个数组都是有序的,所以对于任意二元组 (i,j) 一定出现在 (i-1,j) 和 (i,j-1) 之后。利用这一性质,我们可以声明一个大小为 k 的小根堆,然后首先将 (i,0) 全部放入堆中,之后每次取出一个元素 (i,j),就将候补的 (i,j+1) 放入堆中,直到取够 k 个元素。

参考 cppreference.com,我们给出 lambda 表达式来初始化 comparator 的写法。

参考代码

注意第三个参数需要 decltype(cmp),以及构造函数也必须再次传入 cmp。

/*
 * @lc app=leetcode id=373 lang=cpp
 *
 * [373] Find K Pairs with Smallest Sums
 */

// @lc code=start
class Solution {
public:
    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        assert(k >= 1);
        k = min((size_t)k, nums1.size() * nums2.size());

        using PII = pair<int,int>;
        auto cmp = [&](const PII& a, const PII& b) {
            int sum1 = nums1[a.first] + nums2[a.second];
            int sum2 = nums1[b.first] + nums2[b.second];
            return (sum1 > sum2) || ((sum1 == sum2) && (a.first < b.first));
        }; // vital
        priority_queue<PII, deque<PII>, decltype(cmp)> q(cmp); // vital
        for (int i=0; i<nums1.size() && i<k; i++) {
            q.emplace(i, 0); // (i,0)
        }
        vector<vector<int>> res;
        while (k--) {
            auto [i, j] = q.top();
            q.pop();
            res.push_back({nums1[i], nums2[j]});
            if (j+1 < nums2.size()) {
                q.emplace(i, j+1); // (i,j) -> (i,j+1)
            }
        }
        return res;
    } // AC
};
// @lc code=end

其他题目