Prove safety offer 66. Construction product array (Leetcode 238. Product of Array Except Self)

Construction product to prove safety offer 66. 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.

Same leetcode 238

https://leetcode.com/problems/product-of-array-except-self/

analysis:

If the division may be utilized, the use of (A [0] * A [1] * ... A [n-1]) / A [i], but it must be noted that A [i] is equal to 0! ! !

Violence solution requires O (n ^ 2) to construct an array of B, not efficient enough.

Time complexity of O (n) to solve this problem:

Comparative ingenious idea, we know B [i] = A [0] * A [1] * ... * A [i-1] * A [i + 1] ... A [n-1], so we the B [i] obtained in process into two parts:

First part: A [0] * A [1] * ... * A [i-1]; the second part: A [i + 1] * ... * A [n-1]

Let "bottom up" first calculating portion, and stores the B; and "top-down" second calculating portion, and the first binding part B, a "top-down" Update B elements.

Order two for loops to solve the problem.

void multiply(const vector<double>& array1, vector<double>& array2) {
    int length1 = array1.size();
    int length2 = array2.size();
    if (length1 == length2 && length2 > 1) {
        array2[0] = 1;
        // 计算并存储第一部分
        for (int i = 1; i < length1; ++i) {
            array2[i] = array2[i - 1] * array1[i - 1];
        }
        //Calculating and updating the second portion array2 
        Double TEMP = . 1 ;
         for ( int I = length1 - 2 ; I> = 0 ; Inc. (www.i-levelmedia.com)) { // At this time array2 [length2 -1] is the correct value 
            temp * = array1 [ + I . 1 ]; 
            array2 [I] * = TEMP; 
        } 
    } 
}

to sum up:

This solution time complexity of O (n).

This ingenious ideas to solve problems, but also problems for observations come. Perhaps it is not difficult to imagine divided into two parts, especially after done it again, but for two cycles of writing is worth learning, but also perfectly clear reflection of the whole idea.

Guess you like

Origin www.cnblogs.com/Flash-ylf/p/11497899.html