前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode373. Find K Pairs with Smallest Sums

leetcode373. Find K Pairs with Smallest Sums

作者头像
眯眯眼的猫头鹰
发布2019-03-13 16:47:41
2810
发布2019-03-13 16:47:41
举报
文章被收录于专栏:眯眯眼猫头鹰的小树杈

题目要求

代码语言:javascript
复制
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.

两个单调递增的整数数组,现分别从数组1和数组2中取一个数字构成数对,求找到k个和最小的数对。

思路

这题采用最大堆作为辅助的数据结构能够完美的解决我们的问题。观察数组我们可以看到,从nums1中任意取一个数字,其和nums2中的数字组成的最小数对一定是<nums1[k], nums2[0]>,同理,我们可以知道,<nums1[k], nums2[t+1]>的值一定比nums1[k], nums2[t]大。因此在优先队列中,我们存储所有的nums1中数字所能够构成的最小数对。每从堆中取走一个数对<nums1[k], nums2[t]>,就插入<nums1[k], nums2[t+1]>,从而确保堆中的数对都可以从小到大遍历到。

代码语言:javascript
复制
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> result = new ArrayList<int[]>();
        if(nums1.length == 0 || nums2.length == 0 || k == 0) return result;
        PriorityQueue<int[]> heap = new PriorityQueue<int[]>(new Comparator<int[]>(){

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] + o1[1] - o2[0] - o2[1];
            }});
        
        for(int i = 0 ; i<nums1.length ; i++){
            heap.offer(new int[]{nums1[i], nums2[0], 0});
        }
        while(k-- != 0 && !heap.isEmpty()) {
            int[] min = heap.poll();
            result.add(new int[]{min[0], min[1]});
            if(min[2] == nums2.length) continue;
            heap.offer(new int[]{min[0], nums2[min[2]+1], min[2] + 1});
        }
        return result;
        
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-12-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档