您的位置:首页 > 其它

Product of Array Except Self

2015-09-09 16:03 267 查看
Product of Array Except Self Tota

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.)

Hide Tags Array

Hide Similar Problems (H) Trapping Rain Water (M) Maximum Product Subarray (H) Paint House II

**因为题目要求时间复杂度为O(n^2)且不能用除法,所以不能用先算出sum,再除以num[i]的方法(除数为0,运算不不合法)。

观察图,可知该题目可以用数i左边的数积*数i右边的数积。且可以看做l[0]=1,r[n-1]=1。

最后可知,results[i]=left[i]*right[i].

此算法的复杂度为O(n)**

代码:

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int i;
int len=nums.size();
vector<int> results,left,right;

if(len < 2) return results;

left[0]=1;
right[len-1]=1;
//左边
for(i=0;i<len;i++){
left[i+1]=left[i]*nums[i];
}
//右边
for(i=len-1;i>=1;i--){
right[i-1]=right[i]*nums[i];
}

for(i=0;i<len;i++){
results[i]=left[i]*right[i];
}
return results;
}
};




可参考:http://blog.csdn.net/yangliuy/article/details/46954779
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: