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,2,3,4},1位置上的,为2*3*4,那么结果数组的0位就是24
要求不能使用除法,并且时间复杂度为O(n)
你能在常数空间实现吗?output[]数组的空间不计算在内
分类:数组
解法1:解法有点巧妙。使用一个数组,保存元素组某位置,例如i,保存i前的所以元素的乘积
另外一个数组,保存i后所有元素的乘积
最后这两个数组相乘
public class Solution {
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] output = new int[len];
int[] helper = new int[len];
output[0] = 1;
helper[len-1] = 1;
for(int i=1;i<len;i++){//计算i之前的乘积
output[i] = nums[i-1]*output[i-1];
}
for(int i=len-2;i>=0;i--){//计算i之后的乘积
helper[i] = nums[i+1]*helper[i+1];
}
for(int i=0;i<len;i++){
output[i] = output[i]*helper[i];
}
return output;
}
}
优化一下代码:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] output = new int[len];
int[] helper = new int[len];
output[0] = 1;
helper[len-1] = 1;
for(int i=1;i<len;i++){
output[i] = nums[i-1]*output[i-1];//计算i之前的乘积
helper[len-i-1] = nums[len-i]*helper[len-i];//计算i之后的乘积
}
for(int i=0;i<len;i++){
output[i] = output[i]*helper[i];
}
return output;
}
}