File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ // 풀이 1
3
+ // /**
4
+ // * @param {number[] } nums
5
+ // * @return {number[] }
6
+ // */
7
+ // var productExceptSelf = function(nums) {
8
+ // let hasZero = false;
9
+ // const allProductNums = nums.reduce((acc, cur) => {
10
+ // if (cur === 0) {
11
+ // if (!hasZero) {
12
+ // hasZero = true;
13
+ // return acc;
14
+ // }
15
+
16
+ // return 0;
17
+ // }
18
+ // return acc * cur;
19
+ // }, 1);
20
+
21
+ // return nums.map(num => {
22
+ // if (num === 0) {
23
+ // return allProductNums;
24
+ // }
25
+
26
+ // return hasZero ? 0 : allProductNums / num;
27
+ // });
28
+ // };
29
+
30
+ //풀이 2
31
+ /**
32
+ * @param {number[] } nums
33
+ * @return {number[] }
34
+ */
35
+ var productExceptSelf = function ( nums ) {
36
+ const result = Array ( nums . length ) . fill ( 1 ) ;
37
+
38
+ let beforeProductNum = 1 ;
39
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
40
+ result [ i ] *= beforeProductNum ;
41
+ beforeProductNum *= nums [ i ] ;
42
+ }
43
+
44
+ let afterProductNum = 1 ;
45
+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
46
+ result [ i ] *= afterProductNum ;
47
+ afterProductNum *= nums [ i ] ;
48
+ }
49
+
50
+ return result ;
51
+ } ;
52
+
53
+
54
+ //두 풀이 모두 시간 복잡도 O(n), 공간 복잡도는 O(n)
You can’t perform that action at this time.
0 commit comments