373. Find K Pairs with Smallest Sums
Tried many methods. Take it as a review to heap and piority queue…
- qsort —> time limit exceed
- build min heap, pop the first k pairs —> ac, beat 9%
- use max heap to maintain the k min pairs —> ac, beat 14%
- use the fact that both arrays are presorted, and piority queue to maintain the candidates —> ac, beat 52%
- use built-in library “heapq” —> ac, beat 74%
- use set, instead of array to mark visted slots —> ac, beat 95%
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:
1 | Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3 |
Example 2:
1 | Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2 |
Example 3:
1 | Given nums1 = [1,2], nums2 = [3], k = 3 |
Credits:
Special thanks to @elmirap and @StefanPochmann for adding this problem and creating all test cases.
Soulution:
First we can visualize the all pairs as below:
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | added | added | added | candidate |
1 | added | candidate | ||
2 | candidate |
We observes that, for (i, j), only when (i-1, j) and (i, j-1) are added then it can be a candidate. With this lead, my solution keeps a piority queue, from which the min pair is popped out and then added to the ouput each time. Meanwhile we check if (i, j+1) or (i+1, j) is a valid candidate. If so, add it to the queue. Repeat until ouput has k pairs.
1 | from heapq import * |