查找和最小的K对数字

题目:给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。Leetcode373

示例 1:

输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3          输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

思路:

将所有和可视化为矩阵,最小的一定是左上角,选出3之后,下一个肯定是3的右边或下边,可用堆来实现。

public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        PriorityQueue<Tuple> q = new PriorityQueue<>();
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> one = new ArrayList<>();
        if(nums1==null || nums1.length==0 || nums2==null || nums2.length==0){
            return res;
        }
        int m = nums1.length;
        int n = nums2.length;
        for(int i=0;i<n;i++){
            q.add(new Tuple(0,i,nums1[0]+nums2[i]));
        }
        for(int j=0;j<Math.min(k,m*n);j++){
            Tuple t = q.poll();
            one.add(nums1[t.x]);
            one.add(nums2[t.y]);
            res.add(new ArrayList<Integer>(one));
            one.clear();
            if(t.x==m-1){
                continue;
            }
            q.add(new Tuple(t.x+1,t.y,nums1[t.x+1]+nums2[t.y]));
        }
        return res;
        
    }
    
    class Tuple implements Comparable<Tuple>{
        int x,y,val;
        public Tuple(int x,int y,int val){
            this.x = x;
            this.y = y;
            this.val = val;
        }
        public int compareTo(Tuple that){
           return this.val - that.val;
        }
    

 

同样的解法适用于 Leetcode378

题目:给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
请注意,它是排序后的第k小元素,而不是第k个元素。

示例:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
], k = 8,   返回 13。

public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Tuple> q = new PriorityQueue<>();
        for(int i=0;i<n;i++){
            q.add(new Tuple(0,i,matrix[0][i]));
        }
        for(int j=0;j<k-1;j++){
            Tuple t = q.poll();
            if(t.x==n-1){
                continue;
            }
            q.add(new Tuple(t.x+1,t.y,matrix[t.x+1][t.y]));
        }
        return q.poll().val;
    }
    
    class Tuple implements Comparable<Tuple>{
        int x, y, val;
        public Tuple(int x,int y,int val){
            this.x = x;
            this.y = y;
            this.val = val;
        }
        public int compareTo(Tuple that){
            return this.val - that.val;
        }
    }

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值