【Leetcode】373. Find K Pairs with Smallest Sums

题目地址:

https://leetcode.com/problems/find-k-pairs-with-smallest-sums/

给定两个数组 A A A B B B,返回前 k k k小的 A [ i ] + B [ j ] A[i]+B[j] A[i]+B[j] ( A [ i ] , B [ j ] ) (A[i],B[j]) (A[i],B[j])数对。

思路是堆。开一个class存从 A A A B B B取的是哪两个下标,以及两个数的和。开一个最小堆,先把 ( 0 , 0 ) (0,0) (0,0)加进去,然后每次poll出 ( x , y ) (x,y) (x,y)的时候如果已经poll到第 k k k个了,就停止,否则就将 ( x + 1 , y ) (x+1,y) (x+1,y) ( x , y + 1 ) (x,y+1) (x,y+1)进堆。代码如下:

import java.util.*;

public class Solution {
    
    class Pair {
        int x, y, sum;
        
        public Pair(int x, int y, int sum) {
            this.x = x;
            this.y = y;
            this.sum = sum;
        }
        
        @Override
        public boolean equals(Object o) {
            Pair pair = (Pair) o;
            return x == pair.x && y == pair.y;
        }
        
        @Override
        public int hashCode() {
            return Objects.hash(x, y, sum);
        }
    }
    
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return res;
        }
        
        PriorityQueue<Pair> minHeap = new PriorityQueue<>((p1, p2) -> Integer.compare(p1.sum, p2.sum));
        Pair start = new Pair(0, 0, nums1[0] + nums2[0]);
        minHeap.offer(start);
        Set<Pair> visited = new HashSet<>();
        visited.add(start);
        
        int count = 0;
        while (!minHeap.isEmpty()) {
        	// 把前k个出堆的加入答案
            Pair cur = minHeap.poll();
            res.add(new ArrayList<>(Arrays.asList(nums1[cur.x], nums2[cur.y])));
            count++;
            if (count == k) {
                break;
            }
            
            if (cur.x + 1 < nums1.length) {
                Pair next = new Pair(cur.x + 1, cur.y, nums1[cur.x + 1] + nums2[cur.y]);
                if (!visited.contains(next)) {
                    visited.add(next);
                    minHeap.offer(next);
                }
            }
            
            if (cur.y + 1 < nums2.length) {
                Pair next = new Pair(cur.x, cur.y + 1, nums1[cur.x] + nums2[cur.y + 1]);
                if (!visited.contains(next)) {
                    visited.add(next);
                    minHeap.offer(next);
                }
            }
            
        }
        
        return res;
    }
}

时间复杂度 O ( k log ⁡ k ) O(k\log k) O(klogk),空间 O ( k ) O(k) O(k)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值