您的位置:首页 > 其它

《算法分析与设计》Week 15

2017-06-04 16:56 330 查看
238. Product of Array Except Self

Description:

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

Solution:

一、题意理解
     给定一个包含n(n>1)个整数的数组nums,输出一个数组output,使得output[i]是数组中除了nums[i]的其他所有元素的乘积。要求O(n)时间复杂度,O(1)的空间复杂度。(输出的数组output不计算在内)

二、分析
     1、一个很有意思的题,乍一看,嗯?不是很简单吗?先将数组中所有的数都乘一遍,得到一个总乘积total,output[i] = total / nums[i]。不就行了吗?可是,题中的nums是一个int型的数组,包括正数,负数,当然也包括0,比如nums
= [ 1, 0, 2, 3], 按照这样的思路,output[1] = (1 * 0 * 2 * 3) / 0,明显是不对的。
     2、所以这题并不是那么简单,思考另外一种方式,output[i]等于nums[i]左边数和nums[i]右边的数相乘,那么对于nums[i],我们可以先将nums[0]~nums[i-1]的乘积都算出来,再将nums[i+1]~nums[n-1]的乘积都算出来,再将两个结果相乘,就能得到最终答案。
     3、所以,解题思路就为遍历两次数组,第一次计算左边的乘积,第二次依次计算右边的乘积,再乘以左边的乘积,就是结果。
     4、多说无益,上代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int l = nums.size();
vector<int> output;
output.push_back(1);
for(int i=1; i<l; ++i)
{
output.push_back(output[i-1] * nums[i-1]);
}
int right = 1;
for(int i=l-1; i>=0; --i)
{
output[i] *= right;
right *= nums[i];
}
return output;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: