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
+ function threeSum ( nums : number [ ] ) : number [ ] [ ] {
2
+ // Sort the array to make it easier to find triplets that sum to zero
3
+ nums . sort ( ( a , b ) => a - b ) ;
4
+ const result : number [ ] [ ] = [ ] ;
5
+
6
+ // Iterate through the array to find triplets that sum to zero
7
+ for ( let i = 0 ; i < nums . length - 2 ; i ++ ) {
8
+ // Skip duplicates
9
+ if ( i > 0 && nums [ i ] === nums [ i - 1 ] ) continue ;
10
+
11
+ // Use two pointers to find the other two numbers
12
+ let left = i + 1 ;
13
+ let right = nums . length - 1 ;
14
+
15
+ while ( left < right ) {
16
+ const sum = nums [ i ] + nums [ left ] + nums [ right ] ;
17
+ if ( sum === 0 ) {
18
+ // Add the triplet to the result array
19
+ result . push ( [ nums [ i ] , nums [ left ] , nums [ right ] ] ) ;
20
+ left ++ ;
21
+ right -- ;
22
+ // Skip duplicates
23
+ while ( left < right && nums [ left ] === nums [ left - 1 ] ) left ++ ;
24
+ while ( left < right && nums [ right ] === nums [ right + 1 ] ) right -- ;
25
+ } else if ( sum < 0 ) {
26
+ // Move the left pointer to the right to increase the sum
27
+ left ++ ;
28
+ } else {
29
+ // Move the right pointer to the left to decrease the sum
30
+ right -- ;
31
+ }
32
+ }
33
+ }
34
+
35
+ return result ;
36
+ }
You can’t perform that action at this time.
0 commit comments