Given an integers array A.
Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.
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>(); if(A == null || A.size() == 0) return result; long[] left2curr = new long[A.size()]; long[] curr2right = new long[A.size()]; left2curr[0] = 1; curr2right[A.size() - 1] = 1; for(int i = 1; i < A.size(); i++) left2curr[i] = A.get(i - 1) * left2curr[i - 1]; for(int i = A.size() - 2; i >= 0; i--) curr2right[i] = A.get(i + 1) * curr2right[i + 1]; for(int i = 0; i < A.size(); i++) result.add(left2curr[i] * curr2right[i]); return result; } }
时间: 2024-11-03 21:10:39