File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* -------------------------------------------------------------------------- */
2
+ /* time complexitiy: O(n), space complexitiy: O(n) */
3
+ /* -------------------------------------------------------------------------- */
4
+
5
+ // const productExceptSelf = function (nums) {
6
+ // const result = [];
7
+ // const n = nums.length;
8
+
9
+ // if (n < 2) return result;
10
+
11
+ // const left = [1];
12
+ // const right = [1];
13
+
14
+ // for (let i = 1; i < n; i++) {
15
+ // left[i] = left[i - 1] * nums[i - 1];
16
+ // }
17
+
18
+ // for (let i = 1; i < n; i++) {
19
+ // right[i] = right[i - 1] * nums[n - i];
20
+ // }
21
+
22
+ // for (let i = 0; i < n; i++) {
23
+ // result[i] = left[i] * right[n - 1 - i];
24
+ // if (result[i] === 0) result[i] = Math.abs(result[i]); //0μ΄ -0μΌλ‘ νμλλ μ΄μ νΈλ€
25
+ // }
26
+
27
+ // return result;
28
+ // };
29
+
30
+ /* -------------------------------------------------------------------------- */
31
+ /* time complexitiy: O(n), space complexitiy: O(1) */
32
+ /* -------------------------------------------------------------------------- */
33
+
34
+ const productExceptSelf = function ( nums ) {
35
+ const result = [ 1 ] ;
36
+ const n = nums . length ;
37
+
38
+ if ( n < 2 ) return result ;
39
+
40
+ let prefix = 1 ;
41
+ let postfix = 1 ;
42
+
43
+ for ( let i = 1 ; i < n ; i ++ ) {
44
+ prefix *= nums [ i - 1 ] ;
45
+ result [ i ] = prefix ;
46
+ if ( i === n - 1 && result [ i ] === 0 ) result [ i ] = Math . abs ( result [ i ] ) ; //0μ΄ -0μΌλ‘ νμλλ μ΄μ νΈλ€
47
+ }
48
+
49
+ for ( let i = n - 2 ; i >= 0 ; i -- ) {
50
+ postfix *= nums [ i + 1 ] ;
51
+ result [ i ] *= postfix ;
52
+ if ( result [ i ] === 0 ) result [ i ] = Math . abs ( result [ i ] ) ; //0μ΄ -0μΌλ‘ νμλλ μ΄μ νΈλ€
53
+ }
54
+
55
+ return result ;
56
+ } ;
You canβt perform that action at this time.
0 commit comments