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.)
分析:题目要求不能用除法并且时间复杂度要为O(n),这是本题的难点,本题最直观的解法是用循环遍历,代码如下:
public class Solution { public int[] productExceptSelf(int[] nums) { int [] product = new int[nums.length]; for(int m = 0; m < nums.length; m++){ product[m] = 1; } for(int i = 0; i < nums.length; i++){ for(int j = 0; j < nums.length ; j++){ if(j == i) { continue; } product[i] *= nums[j]; } } return product; } }但是此算法的时间复杂度超过要求,可以选择用两个数组(left[]和right[])来分别接收nums[]数组中从左到右和从右到左相乘,值得一提的是,left[]的首元素代表nums[]第零个元素左边的元素之积,不存在可以赋值为1,同理将right[]数组的最后一位也赋值为1。最终结果数组的第i个元素由左右数组的第i个数据相乘即可得到。
代码:
public class Solution { public int[] productExceptSelf(int[] nums) { int [] product = new int[nums.length]; int [] left = new int[nums.length]; int [] right = new int[nums.length]; left[0] = 1; right[nums.length - 1] = 1; for(int i = 0;i < nums.length - 1;i++){ left[i + 1] = left[i] * nums[i]; } for(int i = nums.length - 1;i > 0; i--){ right[i - 1] = right[i] * nums[i]; } for(int i = 0; i < nums.length; i++){ product[i] = left[i] * right[i]; } return product; } }
代码:
public class Solution { public int[] productExceptSelf(int[] nums) { // int [] product = new int[nums.length]; // int [] left = new int[nums.length]; // int [] right = new int[nums.length]; // left[0] = 1; // right[nums.length - 1] = 1; // for(int i = 0;i < nums.length - 1;i++){ // left[i + 1] = left[i] * nums[i]; // } // for(int i = nums.length - 1;i > 0; i--){ // right[i - 1] = right[i] * nums[i]; // } // for(int i = 0; i < nums.length; i++){ // product[i] = left[i] * right[i]; // } // return product; int [] product = new int[nums.length]; product[0] = 1; for(int i = 0; i < nums.length - 1; i++){ product[i + 1] = product[i] *nums[i]; } int right = 1; for(int i = nums.length - 1; i >= 0; i--){ product[i] *= right; right *= nums[i]; } return product; } }