原题链接在这里:https://leetcode.com/problems/product-of-array-except-self/description/
题目:
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.)
题解:
看到这道题内心十分憎恨自己,这道题在Amazon电面中遇到,当时没有刷题,没有想到这种方法,若是当时刷了题该多好.
leftArr rightArr的方法早已知晓. follow-up 里说不用额外空间,可以采用res数组间接保留leftArr 和 rightArr 数组.
两遍iteration, 第一遍更新左侧, res[i] = left; 第二遍更新右侧, res[i] *= right. 注意一边是是等于,一边是乘等于.
Note: 该i--时不要顺手写成i++.
Method 1 Time Complexity: O(n). Space: O(1).
Method 2 Time Complexity: O(n). Space: O(n), res size.
AC Java:
1 public class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 //Method 1 4 /* 5 if(nums == null || nums.length == 0){ 6 return nums; 7 } 8 int [] index = new int[2]; 9 Arrays.fill(index,-1); 10 int product = 1; 11 12 for(int i = 0; i<nums.length; i++){ 13 product *= nums[i]; 14 if(nums[i] == 0 && index[0] == -1){ 15 index[0] = i; 16 }else if(nums[i] == 0 && index[1] == -1){ 17 index[1] = i; 18 } 19 } 20 if(index[0] == -1){ 21 for(int i = 0; i<nums.length; i++){ 22 nums[i] = product/nums[i]; 23 } 24 }else if(index[1] == -1){ 25 int po = 1; 26 for(int i = 0; i<nums.length; i++){ 27 if(i != index[0]){ 28 po*=nums[i]; 29 } 30 } 31 Arrays.fill(nums,0); 32 nums[index[0]] = po; 33 }else{ 34 Arrays.fill(nums,0); 35 } 36 37 return nums; 38 */ 39 40 //Method 2 41 if(nums == null || nums.length == 0){ 42 return nums; 43 } 44 int [] res = new int[nums.length]; 45 int left = 1; 46 int right = 1; 47 for(int i = 0; i<nums.length; i++){ 48 res[i] = left; 49 left *=nums[i]; 50 } 51 for(int i = nums.length-1; i>=0; i--){ 52 res[i] *=right; 53 right *=nums[i]; 54 } 55 return res; 56 } 57 }