Construction product to prove safety offer 51. Array

Construction product to prove safety offer 51. Array

topic

Given an array A [0,1, ..., n- 1], please construct an array B [0,1, ..., n- 1], where B is the element B [i] = A [ 0] A [. 1] ... A [-I. 1] A [I +. 1] ... A [n--. 1]. You can not use the division. (Note: The predetermined B [0] = A [1 ] * A [2] * ... * A [n-1], B [n-1] = A [0] * A [1] * ... * A [n-2]; )

Thinking

This double desire from the intermediate calculation, first calculates the first part, is the first for loop, for B [i], here it has been multiplied by the first half of a deficit of A [i + 1] of the back, this time second cycle, reverse, give a [len-1], and then forward approximation, provided a temporary variable a represents the product of the latter half.

Code

  public int[] multiply(int[] A) {
    int len = A.length;
    int[] B = new int[len];
    if (len != 0) {
      B[0] = 1;
      for (int i = 1; i < len; i++) {
        B[i] = B[i - 1] * A[i - 1];
      }
      int temp = 1;
      for (int j = len - 2; j >= 0; j--) {
        temp *= A[j + 1];
        B[j] *= temp;
      }
    }
    return B;
  }

Guess you like

Origin www.cnblogs.com/blogxjc/p/12422197.html