题目名称
- Product of Array Except Self
题目描述
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Follow up:
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
初试思路
1、空间换时间,用数组代替一层for循环。
2、重复利用数组空间,避免额外数组,见注释。
初试代码
// 我的代码1
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// res[i] = num[0]*...*nums[i-1]* 1 *nums[i+1]*.. *nums[nums.size()-1]
vector<int> rights(nums.size());
vector<int> results(nums.size());
rights[nums.size()-1] = 1;
for(int i=nums.size()-1; i>0; i--){
rights[i-1] = rights[i] * nums[i];
}
int left = 1;
for(int i=0; i<nums.size(); i++){
results[i] = left * rights[i];
left = left * nums[i];
}
return results;
}
};
// 我的代码2
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// res[i] = num[0]*...*nums[i-1]* 1 *nums[i+1]*.. *nums[nums.size()-1]
//vector<int> rights(nums.size());
vector<int> results(nums.size());
results[nums.size()-1] = 1; //重复利用results来存放rights
for(int i=nums.size()-1; i>0; i--){
results[i-1] = results[i] * nums[i];
}
int left = 1;
for(int i=0; i<nums.size(); i++){
results[i] = left * results[i]; // results[i+1]实际上还是之前算的rights[i+1]的值
left = left * nums[i];
}
return results;
}
};
学到了啥
1、问题拆解:左*右;
2、空间换时间;
3、若额外数组的元素都会只用到一次,则可以用省去该额外数组。