File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n^2)
2+ // Space complexity: O(n)
3+
4+ /**
5+ * @param {number[] } nums
6+ * @return {number[][] }
7+ */
8+ var threeSum = function ( nums ) {
9+ const sumsDict = new Set ( ) ;
10+ const sortedNums = nums . toSorted ( ( a , b ) => a - b ) ;
11+
12+ const n = nums . length ;
13+
14+ for ( let i = 0 ; i < n - 2 ; i ++ ) {
15+ let left = i + 1 ;
16+ let right = n - 1 ;
17+ const fixed = sortedNums [ i ] ;
18+
19+ const targetSum = 0 - fixed ;
20+
21+ while ( left < right ) {
22+ const currentSum = sortedNums [ left ] + sortedNums [ right ] ;
23+
24+ if ( currentSum < targetSum ) {
25+ left ++ ;
26+ } else if ( currentSum > targetSum ) {
27+ right -- ;
28+ } else {
29+ const key = [ fixed , sortedNums [ left ] , sortedNums [ right ] ] ;
30+ sumsDict . add ( key . join ( "," ) ) ;
31+ left ++ ;
32+ right -- ;
33+ }
34+ }
35+ }
36+
37+ return Array . from ( sumsDict ) . map ( ( nums ) => nums . split ( "," ) . map ( Number ) ) ;
38+ } ;
You can’t perform that action at this time.
0 commit comments