原题链接在这里: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]
题解:
类似Kth Smallest Element in a Sorted Matrix.
用nums2当row, nums1当列, nums1的每一个元素依次与nums2中的元素相加 就形成了一个向右向下ascending的matrix.
所以也用一个minHeap来存储第一行,然后poll k次出来加到res中,每次poll出来的元素下面的元素加到minHeap中.
Time Complexity: O(n + klogn), n = min(nums1.length, nums2.length). 选长度较小的array来做row.
Space: O(n), minHeap size.
AC Java:
1 public class Solution { 2 public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) { 3 List<int []> res = new ArrayList<int []>(); 4 if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0 || k <= 0){ 5 return res; 6 } 7 8 PriorityQueue<Tuple> minHeap = new PriorityQueue<Tuple>(); 9 for(int j = 0; j<nums2.length; j++){ 10 minHeap.offer(new Tuple(0, j, nums1[0]+nums2[j])); 11 } 12 for(int p = 0; p<Math.min(k, nums1.length*nums2.length); p++){ 13 Tuple t = minHeap.poll(); 14 res.add(new int[]{nums1[t.i], nums2[t.j]}); 15 if(t.i == nums1.length-1){ 16 continue; 17 } 18 minHeap.offer(new Tuple(t.i+1, t.j, nums1[t.i+1]+nums2[t.j])); 19 } 20 return res; 21 } 22 } 23 24 class Tuple implements Comparable<Tuple>{ 25 int i, j, val; 26 public Tuple(int i, int j, int val){ 27 this.i = i; 28 this.j = j; 29 this.val = val; 30 } 31 32 @Override 33 public int compareTo(Tuple that){ 34 return this.val - that.val; 35 } 36 }