https://leetcode.com/problems/product-of-array-except-self/
两次遍历,第一次保存从左边开始到当前位置前一位的乘积。第二次遍历从右往左,把当前位置右侧的乘积乘上之前保存的值,就是product except self
public class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length <= 1) {
return null;
}
int len = nums.length;
int[] res = new int[len];
res[0] = 1;
for (int i = 1; i < len; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = len - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}