LeetCode 373. Find K Pairs with Smallest Sums

原题链接在这里:https://leetcode.com/problems/find-k-pairs-with-smallest-sums/

题目:

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.

Example 1:

Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3

Return: [1,2],[1,4],[1,6]

The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:

Given nums1 = [1,1,2], nums2 = [1,2,3],  k = 2

Return: [1,1],[1,1]

The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

Example 3:

Given nums1 = [1,2], nums2 = [3],  k = 3 

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

题解:

用nums2当row, nums1当列, nums1的每一个元素依次与nums2中的元素相加 就形成了一个向右向下ascending的matrix.

所以也用一个minHeap来存储第一行, 然后poll k次出来加到res中, 每次poll出来的元素下面的元素加到minHeap中.

Time Complexity: O((n + k) * logn), n = min(nums1.length, nums2.length). 选长度较小的array来做row.

Space: O(n), minHeap size.

AC Java:

 1 class Solution {
 2     public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
 5             return res;
 6         }
 7         
 8         int m = nums1.length;
 9         int n = nums2.length;
10         PriorityQueue<int []> minHeap = new PriorityQueue<>((a, b) -> a[2]-b[2]);
11         for(int j = 0; j<n; j++){
12             minHeap.add(new int[]{0, j, nums1[0]+nums2[j]});
13         }
14         
15         while(k-->0 && !minHeap.isEmpty()){
16             int [] cur = minHeap.poll();
17             res.add(Arrays.asList(nums1[cur[0]], nums2[cur[1]]));
18             if(cur[0] == m-1){
19                 continue;
20             }
21             
22             minHeap.add(new int[]{cur[0]+1, cur[1], nums1[cur[0]+1] + nums2[cur[1]]});
23         }
24         
25         return res;
26     }
27 }

类似Kth Smallest Element in a Sorted Matrix.

跟上Find the Kth Smallest Sum of a Matrix With Sorted Rows.

posted @ 2017-02-02 16:29  Dylan_Java_NYC  阅读(368)  评论(0编辑  收藏  举报