373. Find K Pairs with Smallest Sums
Problem description:
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.
Return the k
pairs (u1, v1), (u2, v2), ..., (uk, vk)
with the smallest sums.
Example 1:
1 | Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 |
Example 2:
1 | Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 |
Example 3:
1 | Input: nums1 = [1,2], nums2 = [3], k = 3 |
Constraints:
1 <= nums1.length, nums2.length <= 104
109 <= nums1[i], nums2[i] <= 109
nums1
andnums2
both are sorted in ascending order.1 <= k <= 1000
Solution:
1 | # # # # # ? . . |
Think like a 2d array, we want to use a priority queue to store some elements to find current minimum.
If we pop out element with j = 0, it means nums[j] would create smaller element, so we keep add column[0] element to heap
1 | class Solution: |
time complexity: $O(klogk)$
space complexity: $O()$
reference:
related problem: