Skip to content

Commit 3f7cefd

Browse files
committed
do 0373
1 parent ee27374 commit 3f7cefd

File tree

1 file changed

+14
-0
lines changed
  • 0301-0400/0351-0400/0373FindKPairsWIthSmallestSums

1 file changed

+14
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from heapq import heappop, heappush
2+
3+
4+
class Solution:
5+
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
6+
M, N = len(nums1), len(nums2)
7+
res = []
8+
pq = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, M))]
9+
while pq and len(res) < k:
10+
_, i, j = heappop(pq)
11+
res.append([nums1[i], nums2[j]])
12+
if j + 1 < N:
13+
heappush(pq, (nums1[i] + nums2[j + 1], i, j + 1))
14+
return res

0 commit comments

Comments
 (0)