@@ -8,37 +8,37 @@ public class FourSumProblem {
8
8
9
9
public static List <List <Integer >> fourSum (int [] nums , int target ) {
10
10
List <List <Integer >> result = new ArrayList <>();
11
-
11
+
12
12
if (nums == null || nums .length < 4 ) {
13
13
return result ; // if array is too small to have 4 numbers, return empty result
14
14
}
15
-
15
+
16
16
// Sort the array first
17
17
Arrays .sort (nums );
18
-
18
+
19
19
// Iterate through the array, fixing the first two elements
20
20
for (int i = 0 ; i < nums .length - 3 ; i ++) {
21
21
if (i > 0 && nums [i ] == nums [i - 1 ]) continue ; // Skip duplicates for the first element
22
22
23
23
for (int j = i + 1 ; j < nums .length - 2 ; j ++) {
24
24
if (j > i + 1 && nums [j ] == nums [j - 1 ]) continue ; // Skip duplicates for the second element
25
-
25
+
26
26
// Use two pointers for the remaining two elements
27
27
int left = j + 1 ;
28
28
int right = nums .length - 1 ;
29
-
29
+
30
30
while (left < right ) {
31
31
int sum = nums [i ] + nums [j ] + nums [left ] + nums [right ];
32
-
32
+
33
33
if (sum == target ) {
34
34
// If we found a quadruplet, add it to the result list
35
35
result .add (Arrays .asList (nums [i ], nums [j ], nums [left ], nums [right ]));
36
-
36
+
37
37
// Skip duplicates for the third element
38
38
while (left < right && nums [left ] == nums [left + 1 ]) left ++;
39
39
// Skip duplicates for the fourth element
40
40
while (left < right && nums [right ] == nums [right - 1 ]) right --;
41
-
41
+
42
42
// Move the pointers
43
43
left ++;
44
44
right --;
@@ -52,7 +52,7 @@ public static List<List<Integer>> fourSum(int[] nums, int target) {
52
52
}
53
53
}
54
54
}
55
-
55
+
56
56
return result ;
57
57
}
58
58
}
0 commit comments