File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ function threeSum ( nums : number [ ] ) : number [ ] [ ] {
2+ const sortedNums = nums . sort ( ( a , b ) => a - b ) ;
3+ const results : number [ ] [ ] = [ ] ;
4+ for ( let i = 0 ; i < sortedNums . length - 2 ; i ++ ) {
5+ const current = sortedNums [ i ] ;
6+ if ( current > 0 ) {
7+ return results ;
8+ }
9+ if ( i > 0 && current === sortedNums [ i - 1 ] ) {
10+ continue ;
11+ }
12+ let left = i + 1 ;
13+ let right = sortedNums . length - 1 ;
14+ while ( left < right ) {
15+ const sum = current + sortedNums [ left ] + sortedNums [ right ] ;
16+ if ( sum > 0 ) {
17+ right -= 1 ;
18+ } else if ( sum < 0 ) {
19+ left += 1 ;
20+ } else {
21+ results . push ( [ current , sortedNums [ left ] , sortedNums [ right ] ] ) ;
22+ left += 1 ;
23+ right -= 1 ;
24+ while ( left < right && sortedNums [ left ] === sortedNums [ left - 1 ] ) {
25+ left += 1 ;
26+ }
27+ while ( left < right && sortedNums [ right ] === sortedNums [ right + 1 ] ) {
28+ right -= 1 ;
29+ }
30+ }
31+ }
32+ }
33+ return results ;
34+ }
You can’t perform that action at this time.
0 commit comments