Question:
Given an array of n integers where n > 1, nums and return an array output such that's equal to output[i] th E 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 solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)
Analysis:
An integer array (n > 1) with n elements is given, nums, which returns an array output, where Output[i] is the product of the other elements except nums[i]. Do not split the array and resolve the problem in O (n) time.
For example to the array: [1, 2, 3, 4], return [24, 12, 8, 6].
Attention:
Can you solve this problem within the constant space complexity? (in the computation of spatial complexity, the output array is not counted)
Analysis:
When calculating multiplication, 0 is a special element, and the question of the sign is considered. So our idea is to:
A. In general (no 0 elements): To avoid overflow, the product of all elements is stored with a long parameter, then the array is looped once, divided by the value of the current element, and the divisor is saved in the output array;
B. If the array contains 0 elements, but we do not know the number of 0 elements, so we need to use another parameter zero to the 0 element count. If the array contains only one 0, then only the 0 element is the product of all other elements, the other elements are 0, and if the array contains an extra 0, all positions are 0.
The subject is very simple, just according to the Special element 0 classification can be.
Answer:
Public classSolution { Public int[] Productexceptself (int[] nums) { Longtemp = 1; intZero = 0; int[] result =New int[Nums.length]; for(intx:nums) { if(x = = 0) Zero++; ElseTemp *=x; } if(Zero > 1) returnresult; Else if(zero = = 1){ for(inti=0; i<nums.length; i++) { if(Nums[i] = = 0) Result[i]= (int) (temp); } returnresult; } Else { for(inti=0; i<nums.length; i++) { if(Nums[i] = = 0) Result[i]= (int) (Temp/Nums[i]); Result[i]= (int) (Temp/Nums[i]); } returnresult; } }}
Leetcode--Product of Array Except self My submissions Question