File tree Expand file tree Collapse file tree
product-of-array-except-self Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // answer[i] -> nums[i] ์ ์ธํ ๋๋จธ์ง์ ๊ณฑ
2+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
3+ let left = [ ] ;
4+ let right = [ ] ;
5+ let acc = 1 ;
6+
7+ for ( let i = 0 ; i < nums . length ; i ++ ) {
8+ left [ i ] = acc ; // ์ด์ ๊ฒฐ๊ณผ๊น์ง์ ๋์ ๊ฐ์ i๋ฒ์งธ์ ์ ์ฅ
9+ acc = acc * nums [ i ] ; // ๋ค์ ์ ์ฅ์ ์ํด ์
๋ฐ์ดํธ
10+ }
11+
12+ acc = 1 ;
13+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
14+ right [ i ] = acc ;
15+ acc = acc * nums [ i ] ;
16+ }
17+
18+ let answer = [ ] ;
19+ for ( let i = 0 ; i < nums . length ; i ++ ) {
20+ answer . push ( left [ i ] * right [ i ] ) ;
21+ }
22+
23+ return answer ;
24+ }
25+
26+ // 2๋ฒ์งธ ์๋
27+ // ๊ณต๊ฐ๋ณต์ก๋๋ฅผ O(1)๋ก ์ค์ผ ์ ์์๊น?
28+ // answer[i] -> nums[i] ์ ์ธํ ๋๋จธ์ง์ ๊ณฑ
29+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
30+ let answer = [ ] ;
31+ let acc = 1 ;
32+
33+ for ( let i = 0 ; i < nums . length ; i ++ ) {
34+ answer [ i ] = acc ; // ์ด์ ๊ฒฐ๊ณผ๊น์ง์ ๋์ ๊ฐ์ i๋ฒ์งธ์ ์ ์ฅ
35+ acc = acc * nums [ i ] ; // ๋ค์ ์ ์ฅ์ ์ํด ์
๋ฐ์ดํธ
36+ }
37+
38+ acc = 1 ;
39+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
40+ answer [ i ] = answer [ i ] * acc ;
41+ acc = acc * nums [ i ] ;
42+ }
43+
44+ return answer ;
45+ }
You canโt perform that action at this time.
0 commit comments