File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * 투 포인터 방식 사용
3
+ * 시간 복잡도: O(n^2)
4
+ * 공간 복잡도; O(n^2)
5
+ */
6
+
7
+ /**
8
+ * @param {number[] } nums
9
+ * @return {number[][] }
10
+ */
11
+ const threeSum = ( nums ) => {
12
+ const sorted = [ ...nums ] . sort ( ( a , b ) => a - b ) ;
13
+ const results = [ ] ;
14
+
15
+ sorted . forEach ( ( val , i ) => {
16
+ if ( i > 0 && val === sorted [ i - 1 ] ) return ;
17
+
18
+ let left = i + 1 ;
19
+ let right = sorted . length - 1 ;
20
+
21
+ while ( left < right ) {
22
+ const sum = val + sorted [ left ] + sorted [ right ] ;
23
+
24
+ if ( sum === 0 ) {
25
+ results . push ( [ val , sorted [ left ] , sorted [ right ] ] ) ;
26
+
27
+ // 중복된 left/right 스킵
28
+ const currentLeft = sorted [ left ] ;
29
+ const currentRight = sorted [ right ] ;
30
+
31
+ while ( left < right && sorted [ left ] === currentLeft ) left ++ ;
32
+ while ( left < right && sorted [ right ] === currentRight ) right -- ;
33
+ } else if ( sum < 0 ) {
34
+ left ++ ;
35
+ } else {
36
+ right -- ;
37
+ }
38
+ }
39
+ } ) ;
40
+
41
+ return results ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments