5
5
public class fourSum {
6
6
public static List <List <Integer >> fourSum (int [] nums , int target ) {
7
7
List <List <Integer >> result = new ArrayList <>();
8
- if (nums == null || nums .length < 4 )
9
- return result ;
8
+ if (nums == null || nums .length < 4 ) return result ;
10
9
11
10
Arrays .sort (nums ); // Sort the array first
12
11
13
12
for (int i = 0 ; i < nums .length - 3 ; i ++) {
14
- if (i > 0 && nums [i ] == nums [i - 1 ])
15
- continue ; // Skip duplicates
13
+ if (i > 0 && nums [i ] == nums [i - 1 ]) continue ; // Skip duplicates
16
14
for (int j = i + 1 ; j < nums .length - 2 ; j ++) {
17
- if (j > i + 1 && nums [j ] == nums [j - 1 ])
18
- continue ; // Skip duplicates
15
+ if (j > i + 1 && nums [j ] == nums [j - 1 ]) continue ; // Skip duplicates
19
16
int left = j + 1 , right = nums .length - 1 ;
20
17
while (left < right ) {
21
18
int sum = nums [i ] + nums [j ] + nums [left ] + nums [right ];
22
19
if (sum == target ) {
23
20
result .add (Arrays .asList (nums [i ], nums [j ], nums [left ], nums [right ]));
24
- while (left < right && nums [left ] == nums [left + 1 ])
25
- left ++; // Skip duplicates
26
- while (left < right && nums [right ] == nums [right - 1 ])
27
- right --; // Skip duplicates
21
+ while (left < right && nums [left ] == nums [left + 1 ]) left ++; // Skip duplicates
22
+ while (left < right && nums [right ] == nums [right - 1 ]) right --; // Skip duplicates
28
23
left ++;
29
24
right --;
30
25
} else if (sum < target ) {
@@ -39,11 +34,11 @@ public static List<List<Integer>> fourSum(int[] nums, int target) {
39
34
}
40
35
41
36
public static void main (String [] args ) {
42
- int [] arr1 = { 1 , 0 , -1 , 0 , -2 , 2 };
37
+ int [] arr1 = {1 , 0 , -1 , 0 , -2 , 2 };
43
38
int target1 = 0 ;
44
39
System .out .println (fourSum (arr1 , target1 ));
45
40
46
- int [] arr2 = { 4 , 3 , 3 , 4 , 4 , 2 , 1 , 2 , 1 , 1 };
41
+ int [] arr2 = {4 , 3 , 3 , 4 , 4 , 2 , 1 , 2 , 1 , 1 };
47
42
int target2 = 9 ;
48
43
System .out .println (fourSum (arr2 , target2 ));
49
44
}
0 commit comments