File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-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
+ nums . sort ( ( a , b ) => a - b ) ; // ์ค๋ฆ์ฐจ์ ์ ๋ ณ
8
+
9
+ // ๋ฐฐ์ด ์์ฐจ ํ์
10
+ for ( let i = 0 ; i < nums . length - 2 ; i ++ ) {
11
+ // ์ค๋ณต ๊ฐ ๊ฑด๋๋
12
+ if ( i > 0 && nums [ i ] === nums [ i - 1 ] ) continue ;
13
+
14
+ let low = i + 1 ,
15
+ high = nums . length - 1 ;
16
+
17
+ // low์ high ํฌ์ธํฐ ์ด์ฉํด ํฉ์ด 0์ธ ๊ฐ ์ฐพ๊ธฐ
18
+ while ( low < high ) {
19
+ const sum = nums [ i ] + nums [ low ] + nums [ high ] ;
20
+ if ( sum < 0 ) low ++ ;
21
+ else if ( sum > 0 ) high -- ;
22
+ else {
23
+ result . push ( [ nums [ i ] , nums [ low ] , nums [ high ] ] ) ;
24
+ // ์ค๋ณต๋ ๊ฐ ๊ฑด๋๋ฐ๊ธฐ
25
+ while ( low < high && nums [ low ] === nums [ low + 1 ] ) low ++ ;
26
+ while ( low < high && nums [ high ] === nums [ high - 1 ] ) high -- ;
27
+ low ++ ;
28
+ high -- ;
29
+ }
30
+ }
31
+ }
32
+
33
+ return result ;
34
+ } ;
35
+
36
+ // 1์๊ฐ ์ ๋ ๋ฌธ์ ํ์ด๋ฅผ ํ๋ค๊ฐ ์ ๋ ฌ๊น์ง ํ ๋ค์ ๊ทธ ์ดํ ์ด๋ป๊ฒ ํด์ผํ ์ง ๋ชฐ๋ผ ํ์ด ์ฐธ๊ณ
37
+ // ๋ฌธ์ ํ์ด์์ ํต์ฌ์ ์ ๋ ฌ์ ํ ๋ค์ ๋ ๊ฐ์ ํฌ์ธํฐ๋ฅผ ์ง์ ํด sum์ด 0์ธ ๊ฐ์ ์ฐพ๋ ๊ฒ
38
+ // ์๊ฐ ๋ณต์ก๋: O(n^2) ๋ฐฐ์ด ์์ฐจ ํ์
39
+ // ๊ณต๊ฐ ๋ณต์ก๋: O(1) ๊ฒฐ๊ณผ๊ฐ result
You canโt perform that action at this time.
0 commit comments