File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(n)
2
+ // Space complexity: O(n)
3
+
4
+ /**
5
+ * @param {number[] } nums
6
+ * @return {number[] }
7
+ */
8
+ var productExceptSelf = function ( nums ) {
9
+ let count0 = 0 ;
10
+
11
+ const totalProduct = nums . reduce ( ( acc , num ) => {
12
+ if ( num === 0 ) {
13
+ count0 ++ ;
14
+ }
15
+
16
+ return acc * num ;
17
+ } , 1 ) ;
18
+
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 ;
32
+ } ) ;
33
+ } ;
You canโt perform that action at this time.
0 commit comments