File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * ์๊ตฌ์ฌํญ
3+ * answer์ด๋ผ๋ ์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ค์ด์ผ ํ๋ค.
4+ * ์ด ๋ฐฐ์ด์์ answer[i]๋
5+ * nums[i] ์๊ธฐ ์์ ์ ์ ์ธํ ๋๋จธ์ง ๋ชจ๋ ์์๋ค์ ๊ณฑ์ด ๋์ด์ผ ํ๋ค.
6+ *
7+ * ํ์ด
8+ * ์๊ธฐ ์์ ์ ์ ์ธํ ๊ณฑ = ์๊ธฐ ์ผ์ชฝ๊น์ง์ ๊ณฑ x ์๊ธฐ ์ค๋ฅธ์ชฝ ๊น์ง์ ๊ณฑ
9+ * => ์ผ์ชฝ ๋์ ๊ณฑ x ์ค๋ฅธ์ชฝ ๋์ ๊ณฑ = answer
10+ * O(n) time, O(1) space
11+ */
12+
13+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
14+ const n = nums . length ;
15+ const result : number [ ] = new Array ( n ) . fill ( n ) ;
16+
17+ let leftProduct = 1 ;
18+ for ( let i = 0 ; i < n ; i ++ ) {
19+ result [ i ] = leftProduct ;
20+ leftProduct *= nums [ i ] ;
21+ }
22+
23+ let rightProduct = 1 ;
24+ for ( let i = n - 1 ; i >= 0 ; i -- ) {
25+ result [ i ] *= rightProduct ;
26+ rightProduct *= nums [ i ] ;
27+ }
28+ return result ;
29+ }
You canโt perform that action at this time.
0 commit comments