Given an array ofNintegers whereN> 1,nums, return an arrayoutputsuch thatoutput[i]is equal to the product of the the elements ofnumsExceptnums[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.)
Thought analysis: The basic idea is to use two arrays left and right,left to save the product of all numbers from the leftmost to the current number, right to save the product of all the numbers from the rightmost to the current, and then the resulting array is to multiply the corresponding positions of the two arrays. If you want to use only O (1) space, you need to re-use the input and output array spaces, the basic idea is to calculate the right array, use the space of the result array to save, and then calculate the left array, only a variable to save the current from the leftmost to the current number of all numbers before the sum. In summary, use the space of the input and output arrays to avoid more spaces. The following comment section code gives a solution to the spatial complexity of O (n), and the non-annotated part gives a solution to the spatial complexity of O (1). The complexity of Time is O (n).
AC Code:
public class Solution {public int[] productexceptself (int[] nums) {/*int len = nums.length; int [] res = new Int[len]; if (Len < 2) return res; int [] left = new Int[len]; int [] right = new Int[len]; Left[0] = 1; Right[len-1] = 1; for (int i = len-1; i > 0; i--) {right[i-1] = right[i] * Nums[i]; } for (int i = 0; i < len-1; i++) {left[i + 1] = left[i] * Nums[i]; } for (int i = 0; i < len; i++) {res[i] = left[i] * Right[i]; } return res;*/int len = nums.length; int [] res = new Int[len]; if (Len < 2) return res; Res[len-1] = 1; for (int i = len-1; i > 0; i--) {res[i-1] = res[i] * Nums[i]; } int left = 1; for (int i = 0; i < len; i++) {res[i] *= left; left = left * Nums[i]; } return res; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Product of Array Except self