File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
leetcode.com 373. Find K Pairs with Smallest Sums Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+ import heapq
3
+
4
+
5
+ class Solution :
6
+ def kSmallestPairs (self , nums1 : List [int ], nums2 : List [int ], k : int ) -> List [List [int ]]:
7
+ answer = []
8
+ heap = []
9
+ visited = set ()
10
+
11
+ heapq .heappush (heap , [nums1 [0 ] + nums2 [0 ], 0 , 0 ])
12
+ visited .add ((0 , 0 ))
13
+
14
+ while k and heap :
15
+ _ , i , j = heapq .heappop (heap )
16
+ answer .append ([nums1 [i ], nums2 [j ]])
17
+ k -= 1
18
+
19
+ if i + 1 < len (nums1 ) and (i + 1 , j ) not in visited :
20
+ heapq .heappush (heap , [nums1 [i + 1 ] + nums2 [j ], i + 1 , j ])
21
+ visited .add ((i + 1 , j ))
22
+
23
+ if j + 1 < len (nums2 ) and (i , j + 1 ) not in visited :
24
+ heapq .heappush (heap , [nums1 [i ] + nums2 [j + 1 ], i , j + 1 ])
25
+ visited .add ((i , j + 1 ))
26
+
27
+ return answer
You can’t perform that action at this time.
0 commit comments