Labels

Sunday, February 8, 2015

Product of Array

Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.
Input : [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]
You must do this in O(N) without using division.
Naive Thinking:这道题想了很久之后我居然想出来一个办法。
要用额外两个数组。
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