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+ * @param {number[] } nums
3+ * @return {number[] }
4+ */
5+ var productExceptSelf = function ( nums ) {
6+ let answer = [ ] ;
7+
8+ const p = [ ] ;
9+ for ( let i = 0 ; i < nums . length ; i ++ ) {
10+ if ( i == 0 ) {
11+ const n = nums . slice ( i + 1 ) . reduce ( ( acc , curr ) => ( acc *= curr ) , 1 ) ;
12+ console . log ( n ) ;
13+ p . push ( [ 1 , n ] ) ;
14+ answer . push ( 1 * n ) ;
15+ } else {
16+ const [ left , right ] = p [ i - 1 ] ;
17+ if ( nums [ i ] === 0 ) {
18+ const n = nums . slice ( i + 1 ) . reduce ( ( acc , curr ) => ( acc *= curr ) , 1 ) ;
19+ p . push ( [ left * nums [ i - 1 ] , n ] ) ;
20+ answer . push ( left * nums [ i - 1 ] * n ) ;
21+ } else {
22+ p . push ( [ left * nums [ i - 1 ] , right / nums [ i ] ] ) ;
23+ answer . push ( ( left * nums [ i - 1 ] * right ) / nums [ i ] ) ;
24+ }
25+ }
26+ }
27+
28+ return answer ;
29+ } ;
You can’t perform that action at this time.
0 commit comments