您的位置:首页 > 编程语言 > C语言/C++

238. Product of Array Except Self

2016-07-16 12:27 344 查看

题目:Product of Array Except Self

原题链接:https://leetcode.com/problems/product-of-array-except-self/

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:

Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

给出一个整数数组(长度大于1),返回一个数组,其中对应每个位置上的元素值为原先数组中不含当前位置元素的其他所有元素的乘积,要求不能用除法,并且线性时间复杂度,并尽量只占用常数个空间用来计算。

例:给出数组 [1,2,3,4], 返回结果应该是 [24,12,8,6].

个人做法可以线性时间复杂度,但是只能达到线性空间复杂度,后面参考网上发现可以优化成常数空间复杂度。

假设初始数组是nums [ ],开两个数组front [ ] 和back [ ], 其中front [ i ] 存放从nums [ 1 ]到 nums [ i - 1 ]的乘积(front [ 1 ]设为1),back [ i ] 存放从nums [ i + 1 ] 到nums [ len - 1 ]的乘积(back [ len - 1 ]设为1 ),这样结果的每一位只要用front [ i ] * back [ i ] 就行了,代码如下:

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len = nums.size();
int front[len], back[len];
vector<int> ans;
for(int i = 0; i < len; ++i){
if(i == 0){
front[i] = 1;
back[len - 1 - i] = 1;
}else{
front[i] = front[i - 1] * nums[i - 1];
back[len - 1 - i] = back[len - i] * nums[len - i];
}
}
for(int i = 0; i < len; ++i){
ans.push_back(front[i] * back[i]);
}
return ans;
}
};


由于开了2个数组,所以目前是线性空间复杂度,优化成O(1)复杂度也很简单,把 front 和 back 从数组换成 int ,然后每次把值直接乘到这两个整型上,然后立刻乘给ans数组就行。代码如下:

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len = nums.size();
int front = 1, back = 1;
vector<int> ans(len,1);
for(int i = 1; i < len; ++i){
front *= nums[i - 1];
ans[i] *= front;
back *= nums[len - i];
ans[len - i -1] *= back;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++