@@ -5,29 +5,31 @@ public List<List<Integer>> threeSum(int[] nums) {
55 if (nums == null || nums .length == 0 ) return res ;
66 Arrays .sort (nums );
77 for (int i = 0 ; i < nums .length ; i ++) {
8- if (i != 0 && nums [i ] == nums [i -1 ]) continue ;
9- List <List <Integer >> tmpRes = twoSum (nums , i );
10- if (tmpRes .size () != 0 ) res .addAll (tmpRes );
8+ if (i > 0 && nums [i ] == nums [i -1 ]) continue ;
9+ List <List <Integer >> tmp = twoSum (nums , i );
10+ if (tmp .size () > 0 ) {
11+ res .addAll (tmp );
12+ }
1113 }
1214 return res ;
1315 }
14-
15- private List <List <Integer >> twoSum (int [] nums , int idx ) {
16+
17+ public List <List <Integer >> twoSum (int [] nums , int idx ) {
1618 int target = -nums [idx ];
17- int left = idx + 1 , right = nums .length - 1 ;
18- List <List <Integer >> tmpRes = new ArrayList <>();
19- while (left < right ) {
20- int sum = nums [left ] + nums [right ];
21- if (sum > target ) right -- ;
22- else if (sum < target ) left ++ ;
19+ int lo = idx + 1 , hi = nums .length - 1 ;
20+ List <List <Integer >> res = new ArrayList <>(3 );
21+ while (lo < hi ) {
22+ int sum = nums [lo ] + nums [hi ];
23+ if (sum < target ) lo ++ ;
24+ else if (sum > target ) hi -- ;
2325 else {
24- tmpRes .add (Arrays .asList (nums [idx ], nums [left ], nums [right ]));
25- while (left < right && nums [left ] == nums [left +1 ]) left ++;
26- while (left < right && nums [right - 1 ] == nums [right ]) right --;
27- left ++;
28- right --;
26+ res .add (Arrays .asList (nums [idx ], nums [lo ], nums [hi ]));
27+ while (lo < hi && nums [lo ] == nums [lo +1 ]) lo ++;
28+ while (lo < hi && nums [hi ] == nums [hi - 1 ]) hi --;
29+ lo ++;
30+ hi --;
2931 }
3032 }
31- return tmpRes ;
33+ return res ;
3234 }
3335}
0 commit comments