数据结构 leetcode 373. Find K Pairs with Smallest Sums

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.

Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. 
vector> kSmallestPairs(vector& nums1, vector& nums2, int k) {
    typedef pair> type;
    priority_queue, greater> que;

    vector> res;

    unordered_set uset;
    que.emplace(make_pair(nums1.front() + nums2.front(), make_pair(0, 0)));

    for (int i = 0; i < k && !queue.empty(); ++i) {
        auto e = que.top();
        que.pop();
        int idx1 = e.second.first;
        int idx2 = e.second.second;
        res.emplace_back(make_pair(nums1[idx1], nums2[idx2]));

        if (idx1 + 1 < nums1.size()) {
            que.emplace(make_pair(nums1[idx1 + 1] + nums2[idx2], make_pair(idx1 + 1, idx2)));
        }
        if (idx1 == 0 && idx2 + 1 < nums2.size()) {
            que.emplace(make_pair(nums1[idx1] + nums2[idx2 + 1], make_pair(idx1, idx2 + 1)));
        }
    }
    return res;
}

你可能感兴趣的:(算法)