题目要求不能用除法,所以还是从乘积入手。
自己写的前缀积 * 后缀积代码,是比较正常的传统解题思路,比较容易想到。
受网友启发
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] resL = new int[len];
resL[0] = nums[0];
int[] resR = new int[len];
resR[len - 1] = nums[len - 1];
for(int i = 1;i < len;i++){
resL[i] = resL[i - 1] * nums[i];
}
for(int i = len - 2;i >= 0;i--){
resR[i] = resR[i + 1] * nums[i];
}
int[] res = new int[len];
for(int i = 0;i < len;i++){
if(i == 0) res[i] = resR[1];
else if(i == len - 1) res[i] = resL[len - 2];
else res[i] = resL[i - 1] * resR[i + 1];
}
return res;
}
将空间复杂度缩小为O(1),不计算输出数组的空间复杂度
代码来源:评论区
https://leetcode-cn.com/problems/product-of-array-except-self/comments/
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int left = 1;
int right = 1;
int[] res = new int[len];
for(int i = 0;i < len;i++){
res[i] = left;
left *= nums[i];
}
for(int i = len - 1;i >= 0;i--){
res[i] *= right;
right *= nums[i];
}
return res;
}
上下三角表格分区思路:
代码来源:
链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public int[] constructArr(int[] a) {
if(a.length == 0) return new int[0];
int[] b = new int[a.length];
b[0] = 1;
int tmp = 1;
for(int i = 1; i < a.length; i++) {
b[i] = b[i - 1] * a[i - 1];
}
for(int i = a.length - 2; i >= 0; i--) {
tmp *= a[i + 1];
b[i] *= tmp;
}
return b;
}
}