资讯专栏INFORMATION COLUMN

leetcode373. Find K Pairs with Smallest Sums

Lavender / 3073人阅读

摘要:题目要求两个单调递增的整数数组,现分别从数组和数组中取一个数字构成数对,求找到个和最小的数对。思路这题采用最大堆作为辅助的数据结构能够完美的解决我们的问题。每从堆中取走一个数对,就插入,从而确保堆中的数对都可以从小到大遍历到。

题目要求
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[t]大。因此在优先队列中,我们存储所有的nums1中数字所能够构成的最小数对。每从堆中取走一个数对,就插入,从而确保堆中的数对都可以从小到大遍历到。

    public List kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List result = new ArrayList();
        if(nums1.length == 0 || nums2.length == 0 || k == 0) return result;
        PriorityQueue heap = new PriorityQueue(new Comparator(){

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] + o1[1] - o2[0] - o2[1];
            }});
        
        for(int i = 0 ; i

想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72557.html

相关文章

  • 373. Find K Pairs with Smallest Sums

    摘要:题目链接先把一组里面和另外一组最小元素的组合放进,然后每次出和最小的,同时放进去有可能成为第二小的组合,即当前元素的下一个和元素的组合。 373. Find K Pairs with Smallest Sums 题目链接:https://leetcode.com/problems... greedy: 先把一组x里面和另外一组y最小元素的组合放进heap,然后每次poll出和最小的,同...

    wing324 评论0 收藏0
  • 373. Find K Pairs with Smallest Sums

    摘要:利用特点进行排序。我们需要构建一个数据结构,一个表示在的位置,一个表示在的位置,他们的和,用来排序。我们首先向里,和所有的元素的和。每次我们一组数,然后增加的会自然的进行排序。 Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Return: [1,2],[1,4],[1,6] The first 3 pairs are returne...

    ningwang 评论0 收藏0
  • 378. Kth Smallest Element in a Sorted Matrix

    摘要:复杂度是,其中。这做法和异曲同工。看了网上给的解法,没有二分,二分的是结果。每次找到一个,然后求比它小的元素的个数,根据个数大于还是小于来二分。参考算的时候可以优化 378. Kth Smallest Element in a Sorted Matrix 题目链接:https://leetcode.com/problems... 求矩阵里面第k小的数,首先比较容易想到的是用heap来做...

    Y3G 评论0 收藏0
  • [LeetCode] Maximum Size Subarray Sum Equals k

    Problem Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isnt one, return 0 instead. Note The sum of the entire nums array is guaranteed to fit ...

    MudOnTire 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<