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.

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 <= 105
  • -109 <= nums1[i], nums2[i] <= 109
  • nums1 and nums2 both are sorted in ascending order.
  • 1 <= k <= 1000

.

代码

class Solution {
public:
    struct cmp {
        bool operator()(pair<int, int>&a, pair<int, int>&b)
        {
            return a.first+a.second < b.first+b.second;
        }
    };
    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        vector<vector<int>> res;
        if(nums1.size() < 1 || nums2.size() < 1)
            return res;
        priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q;
        for(int i = 0; i<nums1.size() && i < k; i++)
        {
            for(int j = 0; j<nums2.size() && j < k; j++)
            {
                if(q.size() < k)
                {
                    q.push(pair<int, int>(nums1[i], nums2[j]));
                }
                else
                {
                    pair<int, int> t = q.top();
                    if(nums1[i] + nums2[j] < t.first + t.second)
                    {
                        q.push(pair<int, int>(nums1[i], nums2[j]));
                        q.pop();
                    }
                }
            }
        }
        while(!q.empty())
        {
            pair<int, int> t = q.top();
            res.push_back({t.first, t.second});
            q.pop();
        }
        return res;
    }
};

.

一道AC之路十分波折的题,还好效率还行,优于75% = =

一直循环着mystery of love,夏天和冬天的感觉同时涌现。
夏天是因为今年的重温,加上故事本身发生在夏天;
恰巧,故事结束在冬天,也或许是以某种形式延续着。
我第一次看这部电影也是在冬天,萧瑟的风带来令人冷静的味道。
需要用心维护美好的故事。
愿世界和平,大家都平平安安,祈祷。

P.S. 一直拖欠的论文笔记今天已经开始写了,九月会更新的~ 对吧!
^______________________________________^*

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值