One. Problem Description
A given length n integer array nums, wherein n> 1, the output returns an array output, wherein the output [i] is equal to the product of the remaining element other than nums [i] nums in.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Do not use a divider, and completed this title in (n) time complexity O.
Advanced:
You can complete this topic yet in constant space complexity? (For the purpose of the space complexity analysis, output array is not considered extra space)
two. Problem-solving ideas
The title ideas: The title dual pointer way to solve, since the subject of the request, please do not use a divider, and in (O n- complete problem within) time complexity, we should take into account the traverse often several times, using the method of the left and right hands will be solving.
Step a: Create two arrays of length n is initialized to the fir and sec 1.
Step Two: Create about pointers, and the second number is traversed from the penultimate number,
for [j] = for [j-1] * nums [j-1];
sec[m]=sec[m+1]*nums[m+1];
Step 3: the array in the array is multiplied by two, the final array output.
three. Results of the
When execution: 1 ms, defeated 100.00% of users in all java submission
Memory consumption: 43.2 MB, defeated 96.20% of all users in java submission
four. Java code
class Solution { public int[] productExceptSelf(int[] nums) { int []fir=new int[nums.length]; int []sec=new int[nums.length]; for(int i=0;i<nums.length;i++) { for [i] = 1 ; sec[i]=1; } for(int j=1,m=nums.length-2;j<nums.length&&m>=0;j++,m--) { for [j] = for [j-1] * nums [j-1 ]; sec[m]=sec[m+1]*nums[m+1]; } for(int k=0;k<nums.length;k++) { for [k] = for [k] * sec [k]; } return fir; } }