|
| 1 | +# 373. Find K Pairs with Smallest Sums |
| 2 | +You are given two integer arrays `nums1` and `nums2` sorted in **non-decreasing order** and an integer `k`. |
| 3 | + |
| 4 | +Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. |
| 5 | + |
| 6 | +Return *the* `k` *pairs* <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> *with the smallest sums*. |
| 7 | + |
| 8 | +#### Example 1: |
| 9 | +<pre> |
| 10 | +<strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3 |
| 11 | +<strong>Output:</strong> [[1,2],[1,4],[1,6]] |
| 12 | +<strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] |
| 13 | +</pre> |
| 14 | + |
| 15 | +#### Example 2: |
| 16 | +<pre> |
| 17 | +<strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2 |
| 18 | +<strong>Output:</strong> [[1,1],[1,1]] |
| 19 | +<strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] |
| 20 | +</pre> |
| 21 | + |
| 22 | +#### Constraints: |
| 23 | +* <code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code> |
| 24 | +* <code>-10<sup>9</sup> <= nums1[i], nums2[i] <= 10<sup>9</sup></code> |
| 25 | +* `nums1` and `nums2` both are sorted in **non-decreasing order**. |
| 26 | +* <code>1 <= k <= 10<sup>4</sup></code> |
| 27 | +* `k <= nums1.length * nums2.length` |
| 28 | + |
| 29 | +## Solutions (Rust) |
| 30 | + |
| 31 | +### 1. Solution |
| 32 | +```Rust |
| 33 | +use std::cmp::Reverse; |
| 34 | +use std::collections::BinaryHeap; |
| 35 | + |
| 36 | +impl Solution { |
| 37 | + pub fn k_smallest_pairs(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> Vec<Vec<i32>> { |
| 38 | + let mut heap = (0..nums1.len().min(k as usize)) |
| 39 | + .map(|i| (Reverse(nums1[i] + nums2[0]), i, 0)) |
| 40 | + .collect::<BinaryHeap<_>>(); |
| 41 | + let mut ret = vec![]; |
| 42 | + |
| 43 | + for _ in 0..k { |
| 44 | + let (_, i, j) = heap.pop().unwrap(); |
| 45 | + |
| 46 | + if j + 1 < nums2.len() { |
| 47 | + heap.push((Reverse(nums1[i] + nums2[j + 1]), i, j + 1)); |
| 48 | + } |
| 49 | + ret.push(vec![nums1[i], nums2[j]]); |
| 50 | + } |
| 51 | + |
| 52 | + ret |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
0 commit comments