(https://leetcode-cn.com/problems/product-of-array-except-self/)
感觉最近的每日一题都挺好玩的,静下心好好想想能体会到久违的思考的乐趣:)
方法一:就是开两个数组,每个数组存前缀积和后缀积,用到的时候直接拿出来相乘就行了
class Solution {
public:
vector<int> ad1,ad2,ans;
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
ad1.resize(n+1);ad2.resize(n+1);
ad1[0] = 1,ad2[n] = 1;
for(int i = 1; i <= n; i++) ad1[i] = ad1[i-1] * nums[i-1];
for(int i = n-1; i >= 0; i--) ad2[i] = ad2[i+1] * nums[i];
for(int i = 0; i < n; i++){
int cnt = ad1[i] * ad2[i+1];
ans.push_back(cnt);
}
return ans;
}
};
方法二:我用的是递归,虽然减少了数组空间,但增加了栈空间,但是再怎么说也是自己想出来的--
class Solution {
public:
vector<int> ans;
int N,right;
void solve(int step,int left,vector<int>& nums){
if(step == N-1){
ans.push_back(left*right);
return;
}
solve(step+1,left*nums[step],nums);
right *= nums[step+1];
ans.push_back(left*right);
}
vector<int> productExceptSelf(vector<int>& nums) {
N = nums.size();
right = 1;
solve(0,1,nums);
reverse(ans.begin(),ans.end());
return ans;
}
};
方法三:官方题解给出的空间O(1)的做法,看完竟然感觉有点...
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
ans[0] = 1;
for (int i = 1; i < n; i++) ans[i] = ans[i-1]*nums[i-1];
int r = 1;
for (int i = n-1; i >= 0; i--){
ans[i] *= r;
r *= nums[i];
}
return ans;
}
};