File tree Expand file tree Collapse file tree 1 file changed +22
-21
lines changed
Expand file tree Collapse file tree 1 file changed +22
-21
lines changed Original file line number Diff line number Diff line change 1515public class Main15 {
1616 public List <List <Integer >> threeSum (int [] nums ) {
1717 List <List <Integer >> res = new ArrayList <>();
18- if (nums == null || nums .length < 3 )
18+ if (nums == null || nums .length < 3 ) {
1919 return res ;
20+ }
2021 Arrays .sort (nums );
21- for (int i = 0 ; i < nums .length -2 ; i ++) {
22- if (nums [i ] > 0 )
23- break ;
24- if (i > 0 && nums [i ]==nums [i -1 ])
25- continue ;
22+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
2623 int left = i + 1 ;
27- int right = nums .length -1 ;
24+ int right = nums .length - 1 ;
25+ if (i != 0 && nums [i ] == nums [i - 1 ]) {
26+ continue ;
27+ }
2828 while (left < right ) {
29- int sum = nums [i ] + nums [left ] + nums [right ];
30- if (sum == 0 ) {
31- res .add (Arrays .asList (nums [i ], nums [left ], nums [right ]));
32- while (left <right && nums [right ] == nums [right -1 ])
33- right --;
34- while (left <right && nums [left ] == nums [left +1 ])
35- left ++;
36- left ++;
37- right --;
38- }
39- else if (sum < 0 )
40- left ++;
41- else if (sum >0 )
42- right --;
29+ if (left != i + 1 && nums [left ] == nums [left - 1 ]) {
30+ left ++;
31+ } else if (right != nums .length - 1 && nums [right ] == nums [right + 1 ]) {
32+ right --;
33+ } else {
34+ if (nums [i ] + nums [left ] + nums [right ] > 0 ) {
35+ right --;
36+ } else if (nums [i ] + nums [left ] + nums [right ] < 0 ) {
37+ left ++;
38+ } else {
39+ res .add (Arrays .asList (nums [i ], nums [left ], nums [right ]));
40+ left ++;
41+ right --;
42+ }
43+ }
4344 }
4445 }
4546 return res ;
You can’t perform that action at this time.
0 commit comments