Skip to content

Commit

Permalink
do 0373
Browse files Browse the repository at this point in the history
  • Loading branch information
BLZbanme committed Jan 14, 2022
1 parent ee27374 commit 3f7cefd
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions 0301-0400/0351-0400/0373FindKPairsWIthSmallestSums/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from heapq import heappop, heappush


class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
M, N = len(nums1), len(nums2)
res = []
pq = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, M))]
while pq and len(res) < k:
_, i, j = heappop(pq)
res.append([nums1[i], nums2[j]])
if j + 1 < N:
heappush(pq, (nums1[i] + nums2[j + 1], i, j + 1))
return res

0 comments on commit 3f7cefd

Please sign in to comment.