Skip to content

Commit bdcd58c

Browse files
committed
Progress: 14/150 - Method 2 Done
1 parent 6983380 commit bdcd58c

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+
// 空间复杂度 O(1) 的方法
2+
// Time Complexity: O(n)
3+
// Space Complexity: O(n)
4+
5+
# include <iostream>
6+
# include <vector>
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
vector<int> productExceptSelf(vector<int>& nums) {
12+
int length = nums.size();
13+
vector<int> answer(length);
14+
15+
// answer[i] 表示索引 i 左侧所有元素的乘积
16+
// 因为索引为 '0' 的元素左侧没有元素, 所以 answer[0] = 1
17+
answer[0] = 1;
18+
for (int i = 1; i < length; i++) {
19+
answer[i] = nums[i - 1] * answer[i - 1];
20+
}
21+
22+
// R 为右侧所有元素的乘积
23+
// 刚开始右边没有元素,所以 R = 1
24+
int R = 1;
25+
for (int i = length - 1; i >= 0; i--) {
26+
// 对于索引 i,左边的乘积为 answer[i],右边的乘积为 R
27+
answer[i] = answer[i] * R;
28+
// R 需要包含右边所有的乘积,所以计算下一个结果时需要将当前值乘到 R 上
29+
R *= nums[i];
30+
}
31+
return answer;
32+
}
33+
};
34+
35+
int main() {
36+
Solution s;
37+
vector<int> nums = {1, 2, 3, 4};
38+
vector<int> answer = s.productExceptSelf(nums);
39+
for (int i = 0; i < answer.size(); i++) cout << answer[i] << " ";
40+
cout << endl;
41+
return 0;
42+
}

0 commit comments

Comments
 (0)