题目(8¥)
题目地址:https://leetcode-cn.com/problems/product-of-array-except-self/submissions/
题解
正向扫一遍,计算每个位置的前缀积;反向扫一遍,计算出每个位置的后缀积后乘以前缀积,保存到 output 数组,得解。
源码
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
int p = 1, q = 1;
for (int i = 0; i < nums.length; i++) {
res[i] = p;
p *= nums[i];
}
for (int i = nums.length - 1; i > 0; i--) {
q *= nums[i];
res[i - 1] *= q;
}
return res;
}
}