解法1
假设使用除法
java
class Solution {
public int[] productExceptSelf(int[] nums) {
int cnt0 = 0, idx0 = 0, lc = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
cnt0++;
idx0 = i;
} else {
lc *= nums[i];
}
}
int[] ans = new int[nums.length];
if (cnt0 == 1) {
ans[idx0] = lc;
} else if (cnt0 < 1) {
for (int i = 0; i < ans.length; i++) {
ans[i] = lc / nums[i];
}
}
return ans;
}
}
解法2
使用额外数组
从左向右乘法,从右向左乘法
java
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
if (n < 2) {
return nums;
}
int[] left = new int[n];
int[] right = new int[n];
int[] ans = new int[n];
int base = 1;
for (int i = 0; i < n; i++) {
base *= nums[i];
left[i] = base;
}
base = 1;
for (int i = n - 1; i > -1; i--) {
base *= nums[i];
right[i] = base;
}
ans[0] = right[1];
ans[n - 1] = left[n - 2];
for (int i = 1; i < n - 1; i++) {
ans[i] = left[i - 1] * right[i + 1];
}
return ans;
}
}
解法3
常数项额外空间
left或者right可以作为最终数组,节约空间。
right动态计算,可以只用一个变量。
java
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
if (n < 2) {
return nums;
}
int[] left = new int[n];
left[0] = 1;
for (int i = 1; i < n; i++) {
left[i] = left[i - 1] * nums[i - 1];
}
int r = 1;
for (int i = n - 2; i > -1; i--) {
r *= nums[i + 1];
left[i] *= r;
}
return left;
}
}