File tree Expand file tree Collapse file tree 1 file changed +11
-20
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +11
-20
lines changed Original file line number Diff line number Diff line change 66 * @return {number[] }
77 */
88var productExceptSelf = function ( nums ) {
9- let count0 = 0 ;
9+ const n = nums . length ;
10+ const fromLeft = Array . from ( { length : n + 1 } , ( ) => 1 ) ;
11+ const fromRight = Array . from ( { length : n + 1 } , ( ) => 1 ) ;
1012
11- const totalProduct = nums . reduce ( ( acc , num ) => {
12- if ( num === 0 ) {
13- count0 ++ ;
14- }
13+ for ( let i = 1 ; i <= n ; i ++ ) {
14+ fromLeft [ i ] = fromLeft [ i - 1 ] * nums [ i - 1 ] ;
15+ }
1516
16- return acc * num ;
17- } , 1 ) ;
17+ for ( let i = n - 1 ; i >= 0 ; i -- ) {
18+ fromRight [ i ] = fromRight [ i + 1 ] * nums [ i ] ;
19+ }
1820
19- return nums . map ( ( num ) => {
20- if ( num === 0 ) {
21- // 0์ด 2 ๊ฐ ์ด์ ์กด์ฌํ ๋
22- if ( count0 > 1 ) {
23- return 0 ;
24- }
25-
26- // 0์ด 1 ๊ฐ ์กด์ฌํ ๋
27- // 0์ ์ ์ธํ ๋๋จธ์ง product ๊ณ์ฐ (์ด ๊ณผ์ ์ ๋จ ํ๋ฒ๋ง ์กด์ฌํ๊ธฐ ๋๋ฌธ์ ์๊ฐ ๋ณต์ก๋๋ ์ฌ์ ํ O(n))
28- return nums . filter ( ( num ) => num !== 0 ) . reduce ( ( a , c ) => a * c , 1 ) ;
29- }
30-
31- return totalProduct / num ;
21+ return nums . map ( ( num , i ) => {
22+ return fromLeft [ i ] * fromRight [ i + 1 ] ;
3223 } ) ;
3324} ;
You canโt perform that action at this time.
0 commit comments