Skip to content

Commit bfd3322

Browse files
committed
product of array except self
1 parent 1d2501f commit bfd3322

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
시간복잡도: O(n) - 배열을 두 번 순회하지만 여전히 선형
3+
배열에서 0의 개수에 따라 결과가 달라지는 점을 이용
4+
- 0이 두 개 이상: 모든 결과는 0
5+
- 0이 하나: 0 위치만 전체곱, 나머지는 0
6+
- 0이 없음: 전체곱 ÷ 현재 원소
7+
*/
8+
9+
/**
10+
* @param {number[]} nums
11+
* @return {number[]}
12+
*/
13+
var productExceptSelf = function (nums) {
14+
// 0이 있는 위치들 체크용
15+
const zeros = new Map();
16+
17+
// 전체 곱 구하기 - O(n)
18+
const allProductExceptZero = nums.reduce((acc, x, i) => {
19+
if (x === 0) zeros.set(i, true);
20+
return x !== 0 ? acc * x : acc;
21+
}, 1);
22+
23+
// 배열 전체 돌면서 조건에 맞게 return 시키기 - O(n)
24+
return nums.map((x, i) => {
25+
// 0이 2개 이상이라면 무조건 0
26+
if (zeros.size > 1) {
27+
return 0;
28+
}
29+
30+
// 0이 1개일 때
31+
if (zeros.size === 1) {
32+
// 그게 나일 때
33+
if (zeros.has(i)) return allProductExceptZero;
34+
35+
// 그게 다른애일 때
36+
return 0;
37+
}
38+
39+
// 0이 없을 때
40+
return allProductExceptZero / x;
41+
});
42+
};

0 commit comments

Comments
 (0)