File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ var productExceptSelf = function ( nums ) {
2
+ const n = nums . length ;
3
+ const left = new Array ( n ) . fill ( 1 ) ;
4
+ const right = new Array ( n ) . fill ( 1 ) ;
5
+ const answer = new Array ( n ) . fill ( 1 ) ;
6
+
7
+ // ์ค๋ฅธ์ชฝ ๋์ ๊ณฑ
8
+ for ( let i = n - 2 ; i >= 0 ; i -- ) {
9
+ right [ i ] = right [ i + 1 ] * nums [ i + 1 ] ;
10
+ }
11
+
12
+ // ์ผ์ชฝ ๋์ ๊ณฑ
13
+ for ( let i = 1 ; i < n ; i ++ ) {
14
+ left [ i ] = left [ i - 1 ] * nums [ i - 1 ] ;
15
+ }
16
+
17
+ // ์ต์ข
๊ณฑ์
18
+ for ( let i = 0 ; i < n ; i ++ ) {
19
+ answer [ i ] = left [ i ] * right [ i ] ;
20
+ }
21
+
22
+ return answer ;
23
+ } ;
24
+ } ;
25
+ //์๊ฐ๋ณต์ก๋ O(n)
26
+ //๊ณต๊ฐ๋ณต์ก๋ O(n)
27
+ // ์ด๋ ค์ ๋ ์ : ํ๋ฒ ํ์๋ ๋ฌธ์ ์ง๋ง, ์ธ๋ฑ์ค ๋ฒ์๋ฅผ ์ค์ ํ๋ ์ ์์ ์ด๋ ค์์ ๊ฒช์๋ค.
28
+
29
+
30
+ //์ฌ๊ธฐ์ ๊ณต๊ฐ๋ณต์ก๋๋ฅผ O(1)๋ก ์ต์ ํ ํ ์ ์๋ค. ( ๋ฆฌํด ๋ฐฐ์ด ์ ์ธ)
31
+ /**
32
+ * ๋ฌธ์ ๋ด์์ Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
33
+ */
34
+ var productExceptSelf = function ( nums ) {
35
+ const n = nums . length ;
36
+ const answer = new Array ( n ) . fill ( 1 ) ;
37
+
38
+ // ์ผ์ชฝ ๊ณฑ
39
+ for ( let i = 1 ; i < n ; i ++ ) {
40
+ answer [ i ] = answer [ i - 1 ] * nums [ i - 1 ] ;
41
+ }
42
+
43
+ // ์ค๋ฅธ์ชฝ ๊ณฑ ๋์ ํ๋ฉด์ answer์ ๊ณฑํด์ค
44
+ let right = 1 ;
45
+ for ( let i = n - 1 ; i >= 0 ; i -- ) {
46
+ answer [ i ] *= right ;
47
+ right *= nums [ i ] ;
48
+ }
49
+
50
+ return answer ;
51
+ } ;
You canโt perform that action at this time.
0 commit comments