Sword refers to Offer 66. Build a product array-Java

Given an array A[0,1,…,n-1], please construct an array B[0,1,…,n-1], where the elements in B are B[i]=A[0]×A [1]×…×A[i-1]×A[i+1]×…×A[n-1]. Division cannot be used.

Example:
Input: [1,2,3,4,5]
Output: [120,60,40,30,24]

Tip: The
sum of the product of all elements will not overflow the 32-bit integer
a.length <= 100000

Source: LeetCode
Link: https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof

the whole idea:

Any element in the result set = product of all elements on its left * product of all elements on its right.
One round of loop builds the product on the left and saves it in the result set, the second loop builds the process of the product on the right, multiplies the product on the left, and saves the final result

  1. Initialization: array B, where B[0] = 1; auxiliary variable tmp = 1;
  2. Calculate the product of each element of the lower triangle of B[i] and directly multiply it into B[i];
  3. Calculate the product of each element of the upper triangle of B[i], record it as tmp, and multiply it into B[i];
  4. Return to B.

Insert picture description here

public int[] constructArr(int[] a) {
    
    
	if(a.length == 0) return new int[0];
	int[] b = new int[a.length];
	b[0] = 1;
	int tmp = 1;
	for(int i = 1; i < a.length; i++) {
    
    
	    b[i] = b[i - 1] * a[i - 1];
	}
	for(int i = a.length - 2; i >= 0; i--) {
    
    
	    tmp *= a[i + 1];
	    b[i] *= tmp;
	}
	return b;
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/107651348