Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Solution:
求出数组的所有乘积和,对应位置除一下。
class Solution {
public int[] productExceptSelf(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
int n = nums.length;
int[] output = new int[n];
int total = 1;
for(int i = 0; i < n; i++) {
total *= nums[i];
}
for(int j = 0; j < n; j++) {
output[j] = total/nums[j];
}
return output;
}
}
但是有个问题,如果输入数组里面有数字为0的话,就会出错,上述程序没有考虑这种情况,优化:
class Solution {
public int[] productExceptSelf(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
int n = nums.length;
int[] output = new int[n];
int total = 1;
for(int i = 0; i < n; i++) {
total *= nums[i];
}
if(total == 0) {
for(int k = 0; k < n; k++) {
output[k] = calculate(nums,k);
}
}else{
for(int j = 0; j < n; j++) {
output[j] = total/nums[j];
}
}
return output;
}
public int calculate(int[] nums,int k) {
int res = 1;
for(int i = 0; i < nums.length; i++) {
if(i == k) {
continue;
}else {
res *= nums[i];
}
}
return res;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)