LeetCode Problem
238. Product of Array Except Self
Link to LeetCode
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
For example, given [1,2,3,4], return [24,12,8,6].
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int[] t1 = new int[nums.length];
int[] t2 = new int[nums.length];
t1[0]=1;
t2[nums.length-1]=1;
//scan from left to right
for(int i=0; i < nums.length-1; i++){
t1[i+1] = nums[i] * t1[i];
}
// scan from right to left
for(int i=nums.length-1; i>0; i--){
t2[i-1] = t2[i] * nums[i];
}
//multiply
for(int i=0; i < nums.length; i++){
result[i] = t1[i] * t2[i];
}
return result;
}
/*
We can directly put the product values into the final result array.
This saves the extra space to store the 2 intermediate arrays in Solution 1.
*/
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
result[nums.length-1]=1;
for(int i=nums.length-2; i>=0; i--){
result[i]=result[i+1]*nums[i+1];
}
int left=1;
for(int i=0; i< nums.length; i++){
result[i]=result[i]*left;
left = left*nums[i];
}
return result;
}