您的位置:首页 > 其它

LeetCode Product of Array Except Self

2015-07-20 19:03 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.)

题意:给出一个数组,求数组中除去其中一个数的乘积

思路:用left[i]表示i左边数的乘积,right[i]表示i右边数的乘积,则output[i] = left[i] *right[i],可以进一步优化,先用output[i]计算出left[i]

代码如下

public class Solution
{
public int[] productExceptSelf(int[] nums)
{
int len = nums.length;
int[] ans = new int[len];

for (int i = 0, tmp = 1; i < len; i++)
{
ans[i] = tmp;
tmp *= nums[i];
}

for (int i = len - 1, tmp = 1; i >= 0; i--)
{
ans[i] *= tmp;
tmp *= nums[i];
}

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