Skip to content

Commit c8db868

Browse files
committed
Solution: Product of Array Except Self
1 parent fdd4d40 commit c8db868

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## Description
2+
3+
한 칸씩 밀린 상태로 누적곱을 배열에 기록해주는 것을 두 번 진행해주면 원하는 바를 얻을 수 있습니다.
4+
5+
| index | 0 | 1 | 2 | 3 |
6+
| ----- | --------- | --------- | --------- | --------- |
7+
| value | 1 | 2 | 3 | 4 |
8+
| acc-> | | 1 | 1 x 2 | 1 x 2 x 3 |
9+
| <-acc | 2 x 3 x 4 | 3 x 4 | 4 | |
10+
| res | 2 x 3 x 4 | 1 x 3 x 4 | 1 x 2 x 4 | 1 x 2 x 3 |
11+
12+
## Big-O
13+
14+
Time complexity: O(N)
15+
16+
Space complexity: O(N)
17+
18+
---
19+
20+
```cpp
21+
class Solution {
22+
public:
23+
vector<int> productExceptSelf(vector<int>& nums) {
24+
vector<int> res(nums.size(), 1);
25+
26+
for (int i = 1; i < nums.size(); i++) {
27+
res[i] *= nums[i - 1] * res[i - 1];
28+
}
29+
30+
int acc = 1;
31+
for (int i = nums.size() - 2; i >= 0; i--) {
32+
acc *= nums[i + 1];
33+
res[i] *= acc;
34+
}
35+
36+
return res;
37+
}
38+
};
39+
```

0 commit comments

Comments
 (0)