Topics
Given an array of n integers where n > 1, nums, return an array output such this output[i] is equal to the product of a ll 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 solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)
Requirements
The topic is better understood, but there are several key points that need to be clarified here:
- You can't use division. It means: You can't come up with the product of all the numbers first, and then divide it by each element, which is boring, technical, and not allowed.
- The complexity of time must be controlled to O (n). The meaning is: if use O (n^2) method, that outer layer A for loop, inside the left and right traverse to solve, also is very boring solution.
- Spatial complexity is best a constant, but the reassigned return array is not counted.
Idea 1
We take an array of 4 elements, for example, NUMS=[A1, A2, A3, A4].
Want to complete the final array output in O (n) time complexity, RES=[A2*A3*A4, A1*A3*A4, A1*A2*A4, A2*a3*a4].
The better solution is to construct a multiplication of two arrays:
- [1, A1, A1*A2, A1*a2*a3]
- [A2*a3*a4, A3*a4, A4, 1]
This way of thinking is not clear a lot, and the two arrays we are relatively good structure.
The AC code is as follows:
Public int[]productexceptself(int[] nums) {intlen = nums.length;int[] Pseq =New int[Nums.length];int[] Nseq =New int[Nums.length]; pseq[0] =1; for(inti =1; i < Len; i + +) {Pseq[i] = pseq[i-1] * Nums[i-1]; } Nseq[len-1] =1; for(inti = len-2; I >=0; I--) {Nseq[i] = nseq[i +1] * nums[i +1]; } for(inti =0; i < Len; i + +) {Pseq[i] *= nseq[i]; }returnPseq; }
However, the spatial complexity above is O (N) and does not satisfy the constant time complexity. The above code can be spatially optimized, with a constant p to hold the result value of each calculation.
Optimized AC code:
int len = nums.lengt h, p; int [] arr = new int [nums.length]; Arr[0 ] = p = 1 ; for (int i = 1 ; i < Len; i + +) {p = p * nums[i-1 ]; Arr[i] = p; } p = 1 ; for (int i = len-2 ; I >= 0 ; I--) {p = p * nums[i + 1 ]; Arr[i] *= p; } return arr;
Idea 2
I thought it was pretty good, but I found a very nice recursive solution in the discuss discussion area, and it's very subtle, and here we share it.
Public int[]Productexceptselfrev(int[] nums) {Multiply (nums,1,0, nums.length);returnNums }Private int Multiply(int[] A,intFwdproduct,intIndxintN) {intRevproduct =1;if(Indx < N) {revproduct = Multiply (A, fwdproduct * a[indx], indx +1, N);intcur = a[indx]; A[INDX] = fwdproduct * REVPRODUCT; Revproduct *= cur; }returnRevproduct; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Product of Array Except Self, Problem solving report