LeetCode 238. Product of Array Except Self
原题链接在这里:https://leetcode.com/problems/product-of-array-except-self/
题目:
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
- The product of any prefix or suffix of
nums
is guaranteed to fit in a 32-bit integer.
题解:
看到这道题内心十分憎恨自己,这道题在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 }