码迷,mamicode.com
首页 > 其他好文 > 详细

Product of Array Exclude Itself

时间:2016-07-01 11:56:28      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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/

Product of Array Exclude Itself

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5632375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!