Tuesday, June 30, 2015

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.
Have you met this question in a real interview? 
Yes

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> result = new ArrayList<Long>();
        int n = A.size();
        long[] lProducts = new long[n];
        long[] rProducts = new long[n];
        lProducts[0] = (long) 1;
        for(int i = 1; i < A.size(); i++){
            lProducts[i] =  (long)lProducts[i-1]*A.get(i-1);
        }
        rProducts[n-1] = (long) 1;
        for(int i = A.size() - 2; i >= 0 ; i--){
            rProducts[i] = (long)rProducts[i+1]*A.get(i+1);
        }
        for(int i = 0; i < A.size(); i++){
            result.add((long)lProducts[i] * rProducts[i]);
        }
        return result;
    }
}

No comments:

Post a Comment