373. Find K Pairs with Smallest Sums
Leetcode HeapYou 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 (u_1,v_1),(u_2,v_2) ...(u_k,v_k) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: 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:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: 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:
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
分析¶
寻找和最小的k对数字。最直接的方法是给出所有的对,一共有n_1 \times n_2对数字,其中n_1和n_2分别为数组nums1和nums2的长度。然后将所有对排序,取出前k对数字。那么怎么排序呢?肯定是必须构造一个Comparator。
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> list = new ArrayList<>();
if (nums1 == null || nums2 == null) return list;
int n1 = nums1.length, n2 = nums2.length;
PriorityQueue<int[]> pq = new PriorityQueue<>(new PairComparator());
for (int i = 0; i < n1; i++)
for (int j = 0; j < n2; j++)
pq.offer(new int[]{nums1[i], nums2[j]});
int bound = Math.min(k, n1*n2);
for (int i = 0; i < bound; i++)
list.add(pq.poll());
return list;
}
class PairComparator implements Comparator<int[]> {
public int compare(int[] one, int[] two) {
return one[0] + one[1] - two[0] - two[1];
}
}
一种更好的方法是使用二叉堆来保存最小对,但是只需要维护K个对即可。因为对于每一个在nums1中的元素来说,对于最小的对,总是从nums2中的第一个元素开始,因为nums2是排序的。所以下一个元素总是nums1[this specific number] + nums2[current_associated_index + 1],除非越界。
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0]+a[1]-b[0]-b[1]);
List<int[]> list = new ArrayList<>();
if (nums1 == null || nums2 == null) return list;
int n1 = nums1.length, n2 = nums2.length;
if (n1 == 0 || n2 == 0 || k == 0) return list;
for (int i = 0; i < n1 && i < k; i++)
// nums1中的值,nums2中的值, nums2的下标
pq.offer(new int[]{nums1[i], nums2[0], 0});
int[] cur;
int bound = Math.min(n1*n2, k);
while (k--> 0 && !pq.isEmpty()){
cur = pq.poll();
list.add(new int[]{cur[0], cur[1]});
if (cur[2] + 1 == n2) continue;
pq.offer(new int[]{cur[0], nums2[cur[2]+1], cur[2]+1});
}
return list;
}