File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @return {number[][] }
4
+ */
5
+ var threeSum = function ( nums ) {
6
+ const result = [ ] ;
7
+ const n = nums . length ;
8
+
9
+ if ( n < 3 ) return result ;
10
+
11
+ nums . sort ( ( a , b ) => a - b ) ;
12
+
13
+ const uniqueTriplets = new Set ( ) ;
14
+
15
+ for ( let i = 0 ; i < n - 2 ; i ++ ) {
16
+ if ( nums [ i ] > 0 ) break ;
17
+
18
+ if ( i > 0 && nums [ i ] === nums [ i - 1 ] ) continue ;
19
+
20
+ const target = - nums [ i ] ;
21
+ const seen = new Set ( ) ;
22
+
23
+ for ( let j = i + 1 ; j < n ; j ++ ) {
24
+ const complement = target - nums [ j ] ;
25
+
26
+ if ( seen . has ( complement ) ) {
27
+ const triplet = [ nums [ i ] , complement , nums [ j ] ] . toString ( ) ;
28
+
29
+ if ( ! uniqueTriplets . has ( triplet ) ) {
30
+ uniqueTriplets . add ( triplet ) ;
31
+ result . push ( [ nums [ i ] , complement , nums [ j ] ] ) ;
32
+ }
33
+ }
34
+
35
+ seen . add ( nums [ j ] ) ;
36
+ }
37
+ }
38
+
39
+ return result ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments