题目
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.
答案
class Solution {
class MyComparator implements Comparator<int[]> {
public int compare(int[] a, int[] b) {
return Integer.compare(a[0] + a[1], b[0] + b[1]);
}
}
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> ret = new ArrayList<>();
Comparator<int[]> comparator = new MyComparator();
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(comparator);
// form all pairs
for(int i = 0; i < nums1.length; i++) {
for(int j = 0; j < nums2.length; j++) {
int[] t = new int[]{nums1[i], nums2[j]};
pq.offer(t);
}
}
// poll k pairs and return
while(!pq.isEmpty() && k > 0) {
ret.add(pq.poll());
k--;
}
return ret;
}
}