Leetcode Product of Array Except Self
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.)
解题思路:
参考答案。
Because we cannot use division, so assume we have two integer arrays with the same length of nums,
int[] leftProd = new int[nums.length]; int[] rightProd = new int[nums.length],
we store the product of all the left elements in leftProd and the product of all the right elements in rightProd,
then the product of leftProd[i] and rightProd[i] will be the value we want to put into the result.
Take the example of num[] = {2, 4, 3, 6}, then leftProd will be {1, 2, 8, 24} , and rightProd will be {72, 18, 6, 1}.
Java code:
public class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; for(int i = 0; i < nums.length; i++) { if( i == 0){ result[i] = 1; }else{ result[i] = result[i-1] * nums[i-1]; } } int prod = 1; for(int i = nums.length-1; i >= 0; i--){ result[i] *= prod; prod *= nums[i]; } return result; } }
Reference:
1. https://leetcode.com/discuss/46150/java-o-n-solution-no-extra-space-with-explanation

浙公网安备 33010602011771号