5
5
import java .util .PriorityQueue ;
6
6
import java .util .Queue ;
7
7
8
- /**
9
- * 373. Find K Pairs with Smallest Sums
10
- *
11
- * You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
12
- * Define a pair (u,v) which consists of one element from the first array and one element from the second array.
13
- * Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
14
-
15
- Example 1:
16
- Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3
17
- Return: [1,2],[1,4],[1,6]
18
- The first 3 pairs are returned from the sequence:
19
- [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
20
-
21
- Example 2:
22
- Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2
23
- Return: [1,1],[1,1]
24
- The first 2 pairs are returned from the sequence:
25
- [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
26
-
27
- Example 3:
28
- Given nums1 = [1,2], nums2 = [3], k = 3
29
- Return: [1,3],[2,3]
30
- All possible pairs are returned from the sequence:
31
- [1,3],[2,3]
32
-
33
- */
34
8
public class _373 {
35
9
public static class Solution1 {
36
10
37
- final int [][] neighbors = new int [][] {{0 , 1 }, {1 , 0 }};
11
+ final int [][] neighbors = new int [][]{{0 , 1 }, {1 , 0 }};
38
12
39
13
public List <int []> kSmallestPairs (int [] nums1 , int [] nums2 , int k ) {
40
14
List <int []> result = new ArrayList <>();
41
15
if (nums1 == null
42
- || nums2 == null
43
- || k == 0
44
- || nums1 .length == 0
45
- || nums2 .length == 0 ) {
16
+ || nums2 == null
17
+ || k == 0
18
+ || nums1 .length == 0
19
+ || nums2 .length == 0 ) {
46
20
return result ;
47
21
}
48
22
Queue <Pair > meanHeap = new PriorityQueue <>();
@@ -51,16 +25,16 @@ public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
51
25
visited [0 ][0 ] = true ;//we start form (0,0), so mark it as visited
52
26
while (k > 0 && !meanHeap .isEmpty ()) {
53
27
Pair pair = meanHeap .poll ();
54
- result .add (new int [] {nums1 [pair .row ], nums2 [pair .col ]});
28
+ result .add (new int []{nums1 [pair .row ], nums2 [pair .col ]});
55
29
k --;
56
30
for (int [] neighbor : neighbors ) {
57
31
int nextRow = pair .row + neighbor [0 ];
58
32
int nextCol = pair .col + neighbor [1 ];
59
33
if (nextRow < 0
60
- || nextCol < 0
61
- || nextRow >= nums1 .length
62
- || nextCol >= nums2 .length
63
- || visited [nextRow ][nextCol ]) {
34
+ || nextCol < 0
35
+ || nextRow >= nums1 .length
36
+ || nextCol >= nums2 .length
37
+ || visited [nextRow ][nextCol ]) {
64
38
continue ;
65
39
}
66
40
visited [nextRow ][nextCol ] = true ;
0 commit comments