Skip to content

Commit c6ef6f4

Browse files
committed
Add solution #373
1 parent 5409641 commit c6ef6f4

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@
292292
368|[Largest Divisible Subset](./0368-largest-divisible-subset.js)|Medium|
293293
371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium|
294294
372|[Super Pow](./0372-super-pow.js)|Medium|
295+
373|[Find K Pairs with Smallest Sums](./0373-find-k-pairs-with-smallest-sums.js)|Medium|
295296
374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium|
296297
378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium|
297298
380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 373. Find K Pairs with Smallest Sums
3+
* https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
4+
* Difficulty: Medium
5+
*
6+
* You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.
7+
*
8+
* Define a pair (u, v) which consists of one element from the first array and one element from the
9+
* second array.
10+
*
11+
* Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums1
16+
* @param {number[]} nums2
17+
* @param {number} k
18+
* @return {number[][]}
19+
*/
20+
var kSmallestPairs = function(nums1, nums2, k) {
21+
const heap = new MinPriorityQueue({ compare: (a, b) => a[0] - b[0] });
22+
const result = [];
23+
24+
for (let i = 0; i < nums1.length; i++) {
25+
heap.enqueue([nums1[i] + nums2[0], 0]);
26+
}
27+
28+
while (k > 0 && !heap.isEmpty()) {
29+
const [n, index] = heap.dequeue();
30+
result.push([n - nums2[index], nums2[index]]);
31+
if (index + 1 < nums2.length) {
32+
heap.enqueue([n - nums2[index] + nums2[index + 1], index + 1]);
33+
}
34+
k--;
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)