topic:
Original link: https://leetcode-cn.com/problems/product-of-array-except-self
Ideas:
- At first I want to use division, first multiply all of them, and then divide each one by the current element value. Then there is a special case of 0, and the title is limited.
- So we can use a similar iterative idea, for each element outside the multiplication and integration into two parts before and after, multiplexing the output array, reducing space occupation
Code:
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
if(nums.length<=0) return result;
// 前缀元素,复用空间
result[0] = 1;
for(int i =1;i<nums.length;i++){
result[i] = result[i-1]*nums[i-1];
}
// 后缀元素
int R = 1;
for(int i = nums.length-1;i>=0;i--){
result[i] = result[i]*R;
R*=nums[i];
}
return result;
}
}