373.Find K Pairs with Smallest Sums
1- Heap
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/discuss/84551/
https://discuss.leetcode.com/topic/52948/share-my-thoughts-and-clean-java-code
class Solution {
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> pQueue = new PriorityQueue<>((a, b) -> (a[0] + a[1] - b[0] - b[1]));
List<int[]> ans = new ArrayList<>();
if(nums1.length==0 || nums2.length==0 || k==0)
return ans;
for(int i = 0; i < nums1.length && i < k; i++){
pQueue.offer(new int[] {nums1[i], nums2[0], 0});
}
for(int i = 0; i < k && !pQueue.isEmpty(); i++){
int[] cur = pQueue.poll();
ans.add(new int[]{cur[0], cur[1]});
if(cur[2] == nums2.length -1){
continue;
}
pQueue.offer(new int[] {cur[0], nums2[cur[2] + 1], cur[2] + 1});
}
return ans;
}
}