[lintcode easy]Product of Array Exclude Itself

Product of Array Exclude Itself

 

Given an integers array A.

Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.

Example

For A = [1, 2, 3], return [6, 3, 2].

 

public class Solution {
    /**
     * @param A: Given an integers array A
     * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
     */
    public ArrayList<Long> productExcludeItself(ArrayList<Integer> A) {
        // write your code
        ArrayList<Long> list=new ArrayList<Long>();
        if(A.size()==0) return list;
        int n=A.size();
        if(n==1) 
        {
            long count=1;
            list.add(count);
            
        }
        
        else{
        for(int i=0;i<n;i++)
        {
            long factor=1;
            for(int j=0;j<n;j++)
            {
                long num=A.get(j);
                if(j==i)
                {
                    num=1;
                }
                factor=num*factor;
            }
            
            list.add(factor);
            
        }
        }
        return list;
    }
}

 

posted on 2015-12-03 04:12  一心一念  阅读(282)  评论(0编辑  收藏  举报

导航