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]
.
分析:
其实这题的限制条件挺脑残的,但是感觉实现的方式还是可以用在其它地方的。
1 public class Solution { 2 /** 3 * @param A: Given an integers array A 4 * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] 5 * cnblogs.com/beiyeqingteng/ 6 */ 7 public ArrayList<Long> productExcludeItself(ArrayList<Integer> A) { 8 ArrayList<Long> result = new ArrayList<Long>(); 9 if (A.size() <= 1) { 10 result.add((long)1); 11 return result; 12 } 13 long[] left = new long[A.size()]; 14 long[] right = new long[A.size()]; 15 left[0] = 1; 16 for (int i = 1; i < A.size(); i++) { 17 left[i] = left[i-1] * A.get(i-1); 18 } 19 right[A.size()-1] = 1; 20 for (int i = A.size()-2; i >= 0; i--) { 21 right[i] = right[i+1] * A.get(i+1); 22 } 23 for (int i = 0; i < A.size(); i++) { 24 result.add(left[i] * right[i]); 25 } 26 return result; 27 } 28 }
转载请注明出处:cnblogs.com/beiyeqingteng/
时间: 2024-10-11 02:51:09