运行两次相同输入数组的循环的复杂性是多少?

时间:2016-06-11 16:01:31

标签: algorithm time-complexity asymptotic-complexity

我是Algorithms的新手,对学习和实现它们非常感兴趣 通过我能找到的所有在线资料学习它们。 对此我有点困惑 -

考虑这段代码 -

for (int i=0; i<n; i++) { ..... }
for (int i=0; i<n; i++) { ..... }

这是什么复杂性?
O(n)或O(n ^ 2)?

3 个答案:

答案 0 :(得分:3)

假设{ . . . }是恒定时间,那么一个循环的复杂度为O(n)。

两个“相邻”循环的复杂性是多少?它是O(n)+ O(n)。或者您可以将其视为O(n + n) - > O(2N)。常量会降低复杂性,因此这是O(n)。

嵌套循环完全不同。以下是:

for (int i=0; i<n; i++) { ..... }
    for (int j=0; j<n; j++) { ..... }

将是O(n ^ 2)。

答案 1 :(得分:1)

复杂性将保持为O(n)

(假设你在for循环中没有另外一个循环)。

答案 2 :(得分:1)

计算时间复杂度背后的想法是你的循环/函数在其中执行每一步的次数?
例如:for循环

for ( int i=0; i < n; i++ ) {
    cout << "hello" << endl;
}

花括号中的代码会打nhello,因此for循环的时间复杂度为O(n)

for ( int i=0; i < n; i++ ) {
    cout << "hello" << endl;
}
for ( int i=0; i < n; i++ ) {
    cout << "hello" << endl;
}

这将比前一次打印hello 2倍,因为它有两个for循环。时间复杂度为O(2n)。我们在计算时间复杂度时忽略常量,因此时间复杂度为O(n)

for ( int i=0; i < n; i++ ) {
    for ( int j=0; j < n; j++ ) {
        cout << "hello" << endl;
    }
}

这会打印hello n^2时间,为什么?因为对于每个外部for loop (i),您执行内部for loop(j) O(n)时间。所以O(n^2)将是时间复杂性

进一步阅读http://www.geeksforgeeks.org/analysis-of-algorithms-set-4-analysis-of-loops/