Leetcode 373. Find K Pairs with Smallest Sums

来源:互联网 发布:mac软件推荐 编辑:程序博客网 时间:2024/06/05 19:32

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.



public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {        Queue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] + a[0] - b[1] - b[0]);        List<int[]> res = new ArrayList<>();        if (nums1.length == 0 || nums2.length == 0 || k == 0) return res;        for (int i = 0; i < nums1.length && i < k; i++) pq.offer(new int[] {nums1[i], nums2[0], 0});        while (k-- > 0 && !pq.isEmpty()) {            int[] cur = pq.poll();            int idx = cur[2];            res.add(new int[] {cur[0], cur[1]});            if (idx == nums2.length - 1) continue;            pq.offer(new int[] {cur[0], nums2[idx + 1], idx + 1});        }        return res;    }









阅读全文
0 0
原创粉丝点击