File tree Expand file tree Collapse file tree 1 file changed +28
-18
lines changed Expand file tree Collapse file tree 1 file changed +28
-18
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
- if (nums == null || nums .length < 3 ) {
3
+ if (nums == null || nums .length == 0 ) {
4
4
return Collections .emptyList ();
5
5
}
6
6
7
- Set <List <Integer >> result = new HashSet <>();
8
-
9
7
Arrays .sort (nums );
10
8
9
+ List <List <Integer >> result = new ArrayList <>();
10
+
11
11
for (int i = 0 ; i < nums .length - 2 ; i ++) {
12
- int j = i + 1 , k = nums .length - 1 ;
13
-
14
- while (j < k ) {
15
- int sum = nums [i ] + nums [j ] + nums [k ];
16
-
17
- if (sum == 0 ) {
18
- result .add (Arrays .asList (nums [i ], nums [j ], nums [k ]));
19
- j ++;
20
- k --;
21
- } else if (sum < 0 ) {
22
- j ++;
23
- } else {
24
- k --;
12
+ if (i == 0 || nums [i ] != nums [i - 1 ]) {
13
+ int j = i + 1 , k = nums .length - 1 ;
14
+
15
+ while (j < k ) {
16
+ int sum = nums [i ] + nums [j ] + nums [k ];
17
+
18
+ if (sum == 0 ) {
19
+ result .add (Arrays .asList (nums [i ], nums [j ], nums [k ]));
20
+
21
+ while (j < k && nums [j ] == nums [j + 1 ]) {
22
+ ++j ;
23
+ }
24
+ while (j < k && nums [k ] == nums [k - 1 ]) {
25
+ --k ;
26
+ }
27
+
28
+ ++j ;
29
+ --k ;
30
+ } else if (sum < 0 ) {
31
+ ++j ;
32
+ } else {
33
+ --k ;
34
+ }
25
35
}
26
36
}
27
37
}
28
38
29
- return new ArrayList <>( result ) ;
39
+ return result ;
30
40
}
31
- }
41
+ }
You can’t perform that action at this time.
0 commit comments