File tree 2 files changed +48
-1
lines changed
src/main/java/com/fibers/algorithm/leetcode/_015
2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change 5
5
target
6
6
* .class
7
7
* .iml
8
+ .classpath
9
+ .project
10
+ .settings /
Original file line number Diff line number Diff line change 1
1
package com .fibers .algorithm .leetcode ._015 ;
2
2
3
+ import com .fibers .utils .Utils ;
4
+
5
+ import java .util .ArrayList ;
6
+ import java .util .Arrays ;
3
7
import java .util .List ;
4
8
5
9
public class Solution {
10
+ public static void main (String [] args ) {
11
+ Solution s = new Solution ();
12
+ int [] ar = new int []{1 , -1 , -1 , 0 };
13
+ Utils .printNestList (s .threeSum (ar ));
14
+ }
15
+
6
16
public List <List <Integer >> threeSum (int [] nums ) {
7
- return null ;
17
+
18
+ List <List <Integer >> results = new ArrayList <>();
19
+ if (nums == null || nums .length < 3 ) {
20
+ return results ;
21
+ }
22
+
23
+ Arrays .sort (nums );
24
+
25
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
26
+ if (i == 0 || (i > 0 && nums [i ] != nums [i - 1 ])) {
27
+ int low = i + 1 ;
28
+ int high = nums .length - 1 ;
29
+ int sum = 0 - nums [i ];
30
+
31
+ while (low < high ) {
32
+ if (nums [low ] + nums [high ] == sum ) {
33
+ results .add (Arrays .asList (nums [i ], nums [low ], nums [high ]));
34
+ while (low < high && nums [low ] == nums [low + 1 ]) {
35
+ low ++;
36
+ }
37
+ while (low < high && nums [high ] == nums [high - 1 ]) {
38
+ high --;
39
+ }
40
+ low ++;
41
+ high --;
42
+ } else if (nums [low ] + nums [high ] < sum ) {
43
+ low ++;
44
+ } else {
45
+ high --;
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ return results ;
8
52
}
9
53
}
You can’t perform that action at this time.
0 commit comments