File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change 1+ // ๋ฐฐ์ด์์ ์ธ๋ฑ์ค์ ์ซ์๋ง ์ ์ธํ ์์์ ๊ณฑ์ ๋ฐฐ์ด์ return ํ๋ ๋ฌธ์
2+
3+ // 1. ์ ์ฒด์ ๊ณฑ์ ๊ตฌํ ๋ค, ํด๋น ์ธ๋ฑ์ค์ ์๋ฅผ ๋๋ ๋ฐฐ์ด์ ๋ง๋ค๋ฉด,
4+ // n์ 2๋ฒ๋ง ๋ฐ๋ณตํ๋ฉด ๋๋ฏ๋ก 2n ์ฆ, O(n)์ผ๋ก ํด๊ฒฐ ๊ฐ๋ฅ
5+
6+ // 2. ํ์ง๋ง ์์ 0์ด ์์ฌ์๋ค๋ฉด?
7+ // 0์ ๊ณฑํ ๊ฒฝ์ฐ๋ ์ ๋ถ 0์ด๋ฏ๋ก ํด๋น ์ผ์ด์ค ๊ณ ๋ ค ํ์
8+ // 0์ด 1๊ฐ์ธ ๊ฒฝ์ฐ 0์ด ์๋ ๋ชจ๋ ์์ ๊ณฑ์ด 0์ธ ์ธ๋ฑ์ค์ ๋ค์ด๊ฐ๊ณ , ๋๋จธ์ง๋ 0
9+ // 0์ด 2๊ฐ ์ด์์ธ ๊ฒฝ์ฐ ์ ๋ถ 0
10+
11+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
12+ const zeroIndices :number [ ] = [ ] ;
13+ nums . forEach ( ( num , index ) => {
14+ if ( num === 0 ) {
15+ zeroIndices . push ( index ) ;
16+ }
17+ } )
18+ if ( zeroIndices . length > 1 ) return Array . from ( { length : nums . length } ) . map ( ( ) => 0 ) ;
19+ const productOfAll = nums . reduce ( ( prev , cur ) => ( cur === 0 ? prev : prev * cur ) , 1 ) ;
20+ if ( zeroIndices . length === 1 ) return Array . from ( { length : nums . length } ) . map ( ( _ , index ) => index === zeroIndices [ 0 ] ? productOfAll : 0 ) ;
21+ return nums . map ( ( num ) => productOfAll / num ) ;
22+ } ;
You canโt perform that action at this time.
0 commit comments