[leetcode] 238. Product of Array Except Self (medium)
原题
思路:
注意时间复杂度,分别乘积左右两边,可达到O(n)
class Solution {
public:
vector<int> productExceptSelf(vector<int> &nums) {
int len = nums.size();
vector<int> res(len, 1);
int left = 1, right = 1;
for (int j = 1; j < len; j++) {
left *= nums[j - 1];
res[j] *= left;
}
for (int i = len - 2; i >= 0; i--) {
right *= nums[i + 1];
res[i] *= right;
}
return res;
}
};