[LeetCode] 238 Product of Array Except Self

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 1. O(n) runtime, O(n) space 
 
 1 class Solution {
 2     public int[] productExceptSelf(int[] nums) {
 3         if(nums == null || nums.length <= 1) {
 4             return nums;
 5         }
 6         int[] leftProduct = new int[nums.length];
 7         leftProduct[0] = nums[0];
 8         for(int i = 1; i < nums.length; i++) {
 9             leftProduct[i] = leftProduct[i- 1] * nums[i];
10         }
11         int[] rightProduct = new int[nums.length];
12         rightProduct[nums.length - 1] = nums[nums.length - 1];
13         for(int i = nums.length - 2; i >= 0; i--) {
14             rightProduct[i] = rightProduct[i + 1] * nums[i];
15         }
16         int[] productArray = new int[nums.length];
17         productArray[0] = rightProduct[1];
18         productArray[nums.length - 1] = leftProduct[nums.length - 2];
19         for(int i = 1; i < nums.length - 1; i++) {
20             productArray[i] = leftProduct[i - 1] * rightProduct[i + 1];
21         }
22         return productArray;
23     }
24 }

 

Solution 2. O(n) runtime, O(1) space, using the output array to store partial left-product results, then update the final product results on a 2nd pass from right to left.

 1 class Solution {
 2     public int[] productExceptSelf(int[] nums) {
 3         if(nums == null || nums.length <= 1) {
 4             return nums;
 5         }
 6         int[] productArray = new int[nums.length];
 7         productArray[0] = 1;
 8         for(int i = 1; i < productArray.length; i++) {
 9             productArray[i] = productArray[i - 1] * nums[i - 1];
10         }
11         int rightProduct = nums[nums.length - 1];
12         for(int i = productArray.length - 2; i >= 0; i--) {
13             productArray[i] *= rightProduct;
14             rightProduct *= nums[i];
15         }
16         return productArray;
17     }
18 }

 

posted @ 2018-11-30 00:18  Review->Improve  阅读(165)  评论(0编辑  收藏  举报