您的位置:首页 > 其它

Product of Array Except Self

2015-11-06 22:32 323 查看

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:起初看到这个题目的时候,第一反应是用先记录所有元素的乘积,然后遍历每个元素,并用该元素去除这个乘积即可,

后来发现若是数组中包含元素0,该方法就会出问题,同时也不符合题意;

思路2:用双重循环去做乘法,但是也不满足题意;

思路3:最后看了一下下面提示的与该题类似的题(trap water),想到用二次遍历,第一次遍历得到当前元素左边元素的乘积,

第二次遍历得到元素右边元素乘积,同时,与上次遍历保存的值做乘法。

代码:

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