LeetCode 373. Find K Pairs with Smallest Sums
Question
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 <= 105
-109 <= nums1[i], nums2[i] <= 109
nums1
andnums2
both are sorted in ascending order.1 <= k <= 104
Source: https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
Solution
This problem is a disguised LeetCode 378. Kth Smallest Element in a Sorted Matrix. We can treat combinations of nums1 and nums2 as a (len1,len2)
matrix. Each element in this matrix is the sum of a pair. Also, this matrix is sorted, which means that every row and column is sorted in ascending order.
1 | static class element { |
LeetCode 373. Find K Pairs with Smallest Sums
http://yenotes.org/2022/03/10/LeetCode-373-Find-K-Pairs-with-Smallest-Sums/