题目描述:
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].
输入数组Nums,返回一个数组output,要求output[i]为,nums[0]...nums[i-1],nums[i+1]....nums[n]的乘积。
思路:
1.区分是否包含0的情况,存0的索引。
2.考虑越界的情况
实现代码:
public class Solution {
public int[] ProductExceptSelf(int[] nums) {
if(nums == null || nums.Length == 1){
return nums;
}
var output = new int[nums.Length];
var zeroIndexes = new List<int>();
for(var i =0 ;i < nums.Length; i++){
if(nums[i] == 0){
zeroIndexes.Add(i);
}
output[i] = 0;
}
if(zeroIndexes.Count > 1){
return output;
}
else if(zeroIndexes.Count == 1){
var s = 1;
for(var i =0 ;i < nums.Length ;i++){
if(i == zeroIndexes[0]){
continue;
}
s *= nums[i];
}
output[zeroIndexes[0]] = s;
return output;
}
else{
output[0] = 1;
for(var i = 1;i < nums.Length; i++){
output[0] *= nums[i];
}
for(var i = 1; i < nums.Length; i++){
try{
output[i] = output[0] * nums [0] % nums[i] == 0 ? output[0] * nums[0] / nums[i] : nums[i] * output[0]/ nums[0];
}
catch(System.OverflowException ex)
{
output[i] = 0;
}
}
}
return output;
}
}