File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+ import java .util .Arrays ;
3
+ import java .util .List ;
4
+
5
+ class Solution {
6
+ public List <List <Integer >> threeSum (int [] nums ) {
7
+ /*
8
+ time complexity: O(n^2)
9
+ space complexity: O(1)
10
+ */
11
+ Arrays .sort (nums );
12
+ List <List <Integer >> result = new ArrayList <>();
13
+
14
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
15
+ if (i > 0 && nums [i ] == nums [i - 1 ]) continue ;
16
+
17
+ int left = i + 1 , right = nums .length - 1 ;
18
+
19
+ while (left < right ) {
20
+ int sum = nums [i ] + nums [left ] + nums [right ];
21
+
22
+ if (sum < 0 ) {
23
+ left ++;
24
+ } else if (sum > 0 ) {
25
+ right --;
26
+ } else {
27
+ result .add (Arrays .asList (nums [i ], nums [left ], nums [right ]));
28
+ while (left < right && nums [left ] == nums [left + 1 ]) left ++;
29
+ while (left < right && nums [right ] == nums [right - 1 ]) right --;
30
+ left ++; right --;
31
+ }
32
+ }
33
+ }
34
+ return result ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments