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;
}
}
博客围绕给定整数数组,要求返回一个数组,其中元素等于原数组除自身外所有元素的乘积。给出了初步求解思路,即求出所有乘积和后对应位置相除,但指出输入数组含0时会出错,需进行优化。
444

被折叠的 条评论
为什么被折叠?



