本题要求是 时间复杂度为 O(n), 空间复杂度为常量,感觉都是满足的
public class Solution {
public int[] productExceptSelf(int[] nums) {
int size = nums.length;
int count = 0; // count记录整个数组中0的数量
int product = 1;
// 计算所有非0数的乘积
for(int i = 0;i<size;i++){
if(nums[i]!=0){
product *= nums[i];
} else {
count ++;
}
}
int[] newNums = new int[size];
if(count > 1) return newNums; // 如果里面有两个0,返回的数组肯定全部都是0
else if(count == 1) { // 一个0的情况下,0处返回全其他数乘积,其他位则都是0
for(int i=0;i<size;i++){
newNums[i] = (nums[i] == 0)?product:0;
}
} else { // 没有0的情况下,每一位返回的都是 乘积除以它自己,就是其他位置的乘积了
for(int i=0;i<size;i++){
newNums[i] = product/nums[i];
}
}
return newNums;
}
}