Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Subscribe to see which companies asked this question
思路:注意分情况讨论,数组里面没有0,一个0,两个以上0都是不一样的情况。
public class Solution {
public int[] productExceptSelf(int[] nums) {
//test if overflow
if(nums.length == 2){
int temp = nums[0];
nums[0] = nums[1];
nums[1] = temp;
return nums;
}
int tProduct = 1;
int zcount = 0;
boolean firstZ = true;
for(int num : nums){
if(num == 0 && firstZ == true){
firstZ = false;
zcount++;
continue;
}
if(num == 0){
zcount++;
}
tProduct *= num;
}
for(int i = 0; i < nums.length; ++i){
if(zcount > 1){
nums[i] = 0;
}else if(zcount == 1){
if(nums[i] != 0){
nums[i] = 0;
}else{
nums[i] = tProduct;
}
}else if(zcount == 0){
nums[i] = tProduct/nums[i];
}
}
return nums;
}
}