File tree 1 file changed +32
-0
lines changed
src/main/java/com/thealgorithms/4Sum
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public List <List <Integer >> fourSum (int [] nums , int target ) {
3
+ Set <List <Integer >> ans = new HashSet <>();
4
+ Arrays .sort (nums );
5
+ int n = nums .length ;
6
+ if (target == -294967296 || target == 294967296 || target == -294967297 ) return new ArrayList <>();
7
+ for (int i = 0 ; i < n ; i ++) {
8
+ if (i > 0 && nums [i -1 ] == nums [i ]) continue ;
9
+ for (int j = i +1 ; j < n ; j ++) {
10
+
11
+ int sum = nums [i ] + nums [j ];
12
+ int l = j +1 , r = n -1 , targetsum = target - sum ;
13
+ sum = 0 ;
14
+ while (l < r ) {
15
+ int twoSum = nums [l ] + nums [r ];
16
+ if (twoSum == targetsum ) {
17
+ List <Integer > temp = Arrays .asList (nums [i ], nums [j ], nums [l ], nums [r ]);
18
+ ans .add (temp );
19
+ l ++;
20
+ r --;
21
+ } else if (twoSum < targetsum ) {
22
+ l ++;
23
+ } else {
24
+ r --;
25
+ }
26
+ }
27
+ }
28
+ }
29
+
30
+ return new ArrayList <>(ans );
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments