原题链接在这里:
题目:
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=0; i--){52 res[i] *=right;53 right *=nums[i];54 }55 return res;56 }57 }