File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } nums
3+ * @return {number[] }
4+ */
5+ var productExceptSelf = function ( nums ) {
6+
7+ const NUMS_LENGTH = nums . length ;
8+ const isZeroArray = [ ] ; //boolean
9+ let zeroCount = 0 ;
10+
11+ let totalProduct = nums . reduce ( ( acc , item ) => {
12+ if ( item === 0 ) {
13+ zeroCount ++ ;
14+ isZeroArray . push ( true ) ;
15+ return acc ;
16+ } else {
17+ isZeroArray . push ( false ) ;
18+ return acc * item ;
19+ }
20+ } , 1 ) ;
21+
22+ // ์ฃ์ง ์ผ์ด์ค ๋๋น 1: nums์ ์์ ์ค 0์ด ๋ ๊ฐ ์ด์์ธ ๊ฒฝ์ฐ
23+ if ( zeroCount >= 2 ) {
24+ totalProduct = 0 ;
25+ }
26+
27+ const tempArray = [ ] ;
28+
29+ for ( let i = 0 ; i < NUMS_LENGTH ; i ++ ) {
30+ if ( isZeroArray [ i ] === true ) {
31+ tempArray . push ( totalProduct ) ;
32+ } else if ( zeroCount >= 1 ) {
33+ // ์ฃ์ง ์ผ์ด์ค ๋๋น 2: isZeroArray[i]๊ฐ false ๋๋ผ๋ nums์ ์์ ์ค zero๊ฐ ํ๋๋ผ๋ ์๋ ๊ฒฝ์ฐ
34+ // (์ง๊ธ ๋ณด๋ ์ด ๋ถ๋ถ์ zeroCount === 1๋ก ํ์ด๋ ๋ ๊ฒ ๊ฐ๋ค์...)
35+ tempArray . push ( 0 ) ;
36+ } else {
37+ tempArray . push ( totalProduct / nums [ i ] ) ;
38+ }
39+ }
40+
41+ return tempArray ;
42+ } ;
43+
You canโt perform that action at this time.
0 commit comments