给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请不要使用除法,且在 O(n) 时间复杂度内完成此题。
示例 1:
输入: nums = [1,2,3,4]
输出: [24,12,8,6]
示例 2:
输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]
提示:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内
ans1.
用除法,不和题意,且效率很低
执行用时:28 ms, 在所有 C++ 提交中击败了21.56%的用户
内存消耗:24.3 MB, 在所有 C++ 提交中击败了45.20%的用户
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int cnt_0 = 0;
int idex_0 = -1;
int n = nums.size();
vector<int> answer;
for(int i = 0;i < n;i++){
answer.push_back(0);
}
for(int i = 0;i < n;i++){
if(nums[i] == 0) {
cnt_0++;
if(idex_0 == -1) idex_0 = i;
// 记录第一个0下标
}
}
if(cnt_0 > 1) return answer;
// 超过一个0,则积全0
long long sum = 1;
for(int j = 0;j < idex_0;++j){
sum *= nums[j];
}
for(int j = idex_0+1;j < n;j++){
sum *= nums[j];
}
if(cnt_0 == 1){
answer[idex_0] = sum;
return answer;
}
for(int i = 0;i < n;i++){
answer[i] = sum/nums[i];
}
return answer;
}
};
ans2.
用两个辅助数组分别存每位的左右乘积
执行用时:16 ms, 在所有 C++ 提交中击败了92.76%的用户
内存消耗:25.6 MB, 在所有 C++ 提交中击败了5.04%的用户
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> Left(n);
vector<int> Right(n);
Left[0] = 1;
Right[n-1] = 1;
// 分别表示下标i元素左边、右边的乘积
for(int i = 1;i < n;i++){
Left[i] = Left[i-1] * nums[i-1];
}
for(int j = n -2;j >= 0;j--){
Right[j] = Right[j+1] * nums[j+1];
}
vector<int> answer;
for(int i = 0;i < n;i++){
answer.push_back(Left[i]*Right[i]);
}
return answer;
}
};
ans3.
直接在输出数组上操作,按题意空间复杂度降为O(n)
执行用时:16 ms, 在所有 C++ 提交中击败了92.76%的用户
内存消耗:23.4 MB, 在所有 C++ 提交中击败了82.28%的用户
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> answer(n);
// 先求出left积
answer[0] = 1;
for(int i = 1;i < n;i++) answer[i] = answer[i-1] * nums[i-1];
// 求right积 并乘left填回answer
int curr = 1;
for(int j = n-2;j >= 0;j--) {
curr *= nums[j+1];
answer[j] = answer[j] * curr;
}
return answer;
}
};