Given an array of numbers,Naive Thinking:这道题想了很久之后我居然想出来一个办法。nums
, return an array of numbersproducts
, whereproducts[i]
is the product of allnums[j], j != i
.
You must do this inInput : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24]
O(N)
without using division.
要用额外两个数组。
num[] =[ 1 2 3 4 5 ]
arr1[] =[ 1 1 2 6 24] 从前往后,arr1[0] = 1, arr1[i] = arr1[i-1]*num[i-1];
arr2[] =[120 60 20 5 1 ] 从后往前,arr2[n] = 1, arr2[i] = arr2[i+1]*num[i+1];
num[] =[120 60 40 30 24] 然后num[i] = arr1[i]*arr2[i]
public class Solution{
public static void main(String args[]){
Solution s = new Solution();
int num[] = {1,2,3,4,5,6,7};
s.productOfArray(num);
for(int i = 0;i < num.length;i++)
System.out.print(num[i] + " ");
}
public void productOfArray(int[] num){
if(num.length < 2){return;}
int arr1[] = new int[num.length];
int arr2[] = new int[num.length];
arr1[0] = 1;arr2[num.length-1] = 1;
for(int i = 1;i < num.length;i++)
arr1[i] = arr1[i-1]*num[i-1];
for(int i = num.length-2;i >= 0;i--)
arr2[i] = arr2[i+1]*num[i+1];
for(int i = 0;i < num.length;i++)
num[i] = arr1[i]*arr2[i];
return;
}
}
No comments:
Post a Comment