How do you determine the complexity of this algorithm in the middle case?

It is usually easy to calculate the time complexity for the best case and the worst case, but when it comes to the average case, especially when there is a probability p, I donโ€™t know where to start.

Let's look at the following algorithm for computing the product of all elements in a matrix:

int computeProduct(int[][] A, int m, int n) {
    int product = 1;
    for (int i = 0; i < m; i++ {
        for (int j = 0; j < n; j++) {
            if (A[i][j] == 0) return 0;
            product = product * A[i][j];
        }
    }
    return product;
}

Suppose p is the probability that it A[i][j]is 0 (i.e., the algorithm terminates there, returns 0); how do we get the average case time complexity for this algorithm?

+6
source share
1 answer

. , , p. , , , ? 1/p,

  • , .
  • Theres p (1-p) , ( , - ).
  • Theres p (1-p) ^ 2 , ( , )
  • ...
  • Theres a p (1-p) ^ (k-1) , k flips ( k-1 , kth .)

, ,

p + 2p (1 - p) + 3p (1 - p) ^ 2 + 4p (1 - p) ^ 3 +...

= p (1 (1 - p) ^ 0 + 2 (1 - p) ^ 1 + 3 (1 - p) ^ 2 +...)

, , .

p sum k = 1 (k (1 - p) ^ k).

, , . x - , โ€‹โ€‹ 1 - p, .

p sum k = 1 (kx ^ (k-1)).

: , x ^ k x. ,

p sum k = 1 (d/dx x ^ k).

, :

p d/dx sum k = 1 (x ^ k)

(x + x ^ 2 + x ^ 3 +...) 1/(1 - x) - 1, ,

p d/dx (1/(1 - x) - 1)

= p/(1 - x) ^ 2

x = 1 - p,

p/(1 - (1 - p)) ^ 2

= p/p ^ 2

= 1/p

! . , 1/p.

, , mn, p , - . , , , , , , O (1/p) ( , p > 0).

, p m n, , . , . , mn , & theta; (log p), , & theta; (1/p). , O, mn p, & Theta; (1/p).

+3

All Articles