以下代码段的时间复杂度是多少?

时间:2019-01-05 22:24:55

标签: time-complexity big-o

我需要帮助来确定代码段的时间复杂度。

我试图了解如何添加所有内容,但是我不确定它是否正确。以我的理解,第一个循环和第二个循环是对数的,最后一个是线性的,或者至少是我想的。但是我不明白如何解决问题并提供时间复杂性。

sum = 0; count = 0;
for (int i = 1; i < N; i = i*2){
    sum = sum + 1;
    for (int j = i; j < N*N; j = j*2){
        count++;
    }
    for (int k = i; k < N; k++){
        count--;
    }
}

我的猜测是:(logN * logN)+(logN * N)-> O(NlogN) 但是由于第三个循环没有嵌套在第二个循环中,所以我不确定如何正确确定复杂性。所以请帮助我.. :)

1 个答案:

答案 0 :(得分:0)

Assume first N=2^M. Then M = lg(N).

The outer loop runs for i = 2^0, 2^1, 2^2, ..., 2^(M-1). A total of M steps.

The first inner loop runs for j = 2^s, ..., 2^(M + M - 1) in step s (out of Msteps). Total 2M-s.

The second runs for k = 2^s, 2^s + 1, ..., 2^M - 1 in step s. Total 2^M - 2^s.

The first loop takes a total of (2M-0) + (2M-1) + ... + (2M - (M-1)) which is O(M^2) = O(lg(N)^2).

The second (2^M-2^0) + ... + (2^M-2^(M-1)), which equals M2^M - 2^M + 1, which is O(M2^M) = O(Nlg(N)).

Therefore the total complexity is O(lg(N)lg(N)) + O(Nlg(N)) = O(Nlg(N)).

For the general case, where N is not a power of two, consider M such that 2^M < N < 2^(M+1) and conclude that the complexity remains O(Nlg(N)).