238. Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Approach
- 题目大意很明显就直接讲思路,因为题目有注明说不能使用除,一开始自己没有想出如何不用除可以解决,思路很简单就是将所有结果相乘,然后到哪个数就除掉哪个数即可,当然前面这些操作是不能有零的,所以需要分类讨论,当有一个零和多个零,以及没有零的情况。当只有一个零的时候,那么除了等于零的地方是非零,其他地方都是零,当多个零的时候,所有都是零,没有零就是刚开始的操作。32ms
Code
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int sum = 1, cnt = 0, N = nums.size();
for (int i = 0; i < N; i++) {
if (nums[i])
sum *= nums[i];
else
cnt++;
}
if (cnt > 1)
return vector<int>(N, 0);
vector<int>ans;
if (cnt == 1) {
for (int i = 0; i < N; i++) {
if (nums[i] == 0)ans.push_back(sum);
else ans.push_back(0);
}
return ans;
}
for (int i = 0; i < N; i++) {
ans.push_back(sum / nums[i]);
}
return ans;
}
};
Again
- 看了一下人家提交的代码,发现可以先前缀乘,然后再后缀乘,那么就可以达到不用除的目的,思路很巧。
Code
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int N = nums.size();
vector<int> res(N, 1);
for (int i = 1; i < N; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = N - 1; i >= 0; i--) {
res[i] = res[i] * right;
right =right* nums[i];
}
return res;
}
};