class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> answer(n);
answer[0] = 1;
//先计算出所有元素的左元素之积
for(int i = 1; i < n; i++){
answer[i] = answer[i - 1] * nums[i - 1];
}
//再在上面的基础上加上右元素之积
int R = 1; //避免乘上本身,也可以R = nums[n - 1],然后循环从n - 2开始
for(int i = n - 1; i >= 0; i--){
answer[i] = answer[i] * R;
R = R * nums[i];
}
return answer;
}
};
Accepted
20/20 cases passed (24 ms)
Your runtime beats 44.82 % of cpp submissions
Your memory usage beats 72.64 % of cpp submissions (23.4 MB)