55public class fourSum {
66 public static List <List <Integer >> fourSum (int [] nums , int target ) {
77 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 ;
109
1110 Arrays .sort (nums ); // Sort the array first
1211
1312 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
1614 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
1916 int left = j + 1 , right = nums .length - 1 ;
2017 while (left < right ) {
2118 int sum = nums [i ] + nums [j ] + nums [left ] + nums [right ];
2219 if (sum == target ) {
2320 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
2823 left ++;
2924 right --;
3025 } else if (sum < target ) {
@@ -39,11 +34,11 @@ public static List<List<Integer>> fourSum(int[] nums, int target) {
3934 }
4035
4136 public static void main (String [] args ) {
42- int [] arr1 = { 1 , 0 , -1 , 0 , -2 , 2 };
37+ int [] arr1 = {1 , 0 , -1 , 0 , -2 , 2 };
4338 int target1 = 0 ;
4439 System .out .println (fourSum (arr1 , target1 ));
4540
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 };
4742 int target2 = 9 ;
4843 System .out .println (fourSum (arr2 , target2 ));
4944 }
0 commit comments