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

【leetcod】Product of Array Except Self -C++

2015-09-09 17:29 507 查看
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.)

大意:给一个数组a,然后返回一个数组b,b数组中的数是对应的是a数组中除了自己以外剩下所有数的乘积。不能使用除法。

假设数组为:

a1,a2,a3,a4

可以创建两个有规律数组

1,a1,a1a2,,a1a2a3

a2a3a4,a3a4,a4,1

然后对应相乘就可以了。

还可以只创建一个数组 1,a1,a1a2,,a1a2a3,此时最后一项已经对了,只差前面的了,然后逆序遍历,用一个临时变量来存储要乘的数据。

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
if(nums.size() <= 1)
{
vector<int> ivec(nums.begin(),nums.end());
return ivec;
}
vector<int> ivec(nums.size(),1);
for(int i = 1;i < nums.size();++i)
{
ivec[i] = ivec[i-1] * nums[i-1];
}
int numtmp = 1;
for(int i = nums.size() - 1; i >= 0;--i)
{
ivec[i] = ivec[i] * numtmp;
numtmp *= nums[i];
}
return ivec;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: