File tree 1 file changed +13
-20
lines changed
1 file changed +13
-20
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public List <List <Integer >> threeSum (int [] nums ) {
3
3
Arrays .sort (nums );
4
- List <List <Integer >> list = new ArrayList <>();
4
+ List <List <Integer >> result = new ArrayList <>();
5
5
for (int i = 0 ; i < nums .length && nums [i ] <= 0 ; i ++) {
6
6
if (i == 0 || nums [i - 1 ] != nums [i ]) {
7
- twoSumHelper (nums , i , list );
8
- }
9
- }
10
- return list ;
11
- }
12
-
13
- private void twoSumHelper (int [] nums , int i , List <List <Integer >> list ) {
14
- int low = i + 1 ;
15
- int high = nums .length - 1 ;
16
- while (low < high ) {
17
- int sum = nums [i ] + nums [low ] + nums [high ];
18
- if (sum < 0 || (low > i + 1 && nums [low ] == nums [low - 1 ])) {
19
- low ++;
20
- }
21
- else if (sum > 0 || (high < nums .length - 1 && nums [high ] == nums [high + 1 ])) {
22
- high --;
23
- }
24
- else {
25
- list .add (Arrays .asList (nums [i ], nums [low ++], nums [high --]));
7
+ Set <Integer > set = new HashSet <>();
8
+ for (int j = i + 1 ; j < nums .length ; j ++) {
9
+ int target = -1 * (nums [i ] + nums [j ]);
10
+ if (set .contains (target )) {
11
+ result .add (Arrays .asList (nums [i ], nums [j ], target ));
12
+ while (j + 1 < nums .length && nums [j ] == nums [j + 1 ]) {
13
+ j ++;
14
+ }
15
+ }
16
+ set .add (nums [j ]);
17
+ }
26
18
}
27
19
}
20
+ return result ;
28
21
}
29
22
}
You can’t perform that action at this time.
0 commit comments