Skip to content

Commit 7a591de

Browse files
committed
using min heap to find k smallest pairs from two arrays
1 parent 410827f commit 7a591de

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Two Pointers/kSmallestPairs.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
// O(KlogK) solution
3+
/*
4+
Putting all the elements combination from one array element to other and then
5+
traversing in second array to find other smallest pairs.
6+
*/
7+
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
8+
List<List<Integer>> finalRes = new ArrayList<>();
9+
if(nums1.length==0 || nums2.length==0 || k==0) return finalRes;
10+
int len1 = nums1.length;
11+
int len2 = nums2.length;
12+
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> (a[0] + a[1]) - (b[0]+ b[1]));
13+
for (int i=0; i<len1&& i<k; i++){
14+
pq.offer(new int[]{nums1[i], nums2[0], 0}); //storing index of nums2 traversal
15+
}
16+
while(k-- > 0 && !pq.isEmpty()) {
17+
int[] cur = pq.poll();
18+
List<Integer> res = new ArrayList<>();
19+
res.add(cur[0]);
20+
res.add(cur[1]);
21+
finalRes.add(res);
22+
int num2index = cur[2];
23+
if(num2index + 1 < nums2.length){
24+
pq.offer(new int[]{cur[0],nums2[num2index+1], num2index+1});
25+
}
26+
}
27+
return finalRes;
28+
}
29+
}

0 commit comments

Comments
 (0)