您的位置:首页 > 其它

Product of Array Except Self

2015-07-16 10:30 218 查看
问题描述

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. 使用辅助空间

为方便理解,使用两个与输入数组同等大小的辅助数组

首先,从前到后扫描数组,一个数组[i]存储的是除了当前元素外的所有前面元素的乘积;

然后,从后到前扫描数组,另一个数组[i]存储的是除了当前元素外的所有后面元素的乘积。

最后将这两个数组的对应位置的元素相乘即可。

优化后可以省略一个数组和一遍扫描。

程序

public class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null) {
return null;
}
int len = nums.length;
int[] res = new int[len];
int[] tmp = new int[len];
tmp[0] = 1;
res[0] = 1;

for (int i = 1; i < len; i++) {
tmp[i] = tmp[i - 1] * nums[i - 1];
res[i] = tmp[i];
}
tmp[len - 1] = 1;
for (int i = len - 2; i >= 0; i--) {
tmp[i] = tmp[i + 1] * nums[i + 1];
res[i] *= tmp[i];
}

return res;
}
}


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