What is the time complexity of the following algorithm?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 08:04:34

问题


for (int i = 0; i < n; i++ ) {
    for (int j = 0; j < n; j++ {
        Simple Statement
    }
}
for (int k = 0; i < n; k++ {
    Simple Statement
    Simple Statement
    Simple Statement
    Simple Statement
    Simple Statement
}
    Simple Statement*25

For the nested loop, I find a time complexity of 1 (for int i = 0) + n + 1 (for i < n) + n (for i++) * [ 1 (for int j = 0 ) + 1 + n ( for j < n) + n ( for j++) ] + n (for the simple statement). This is (1+n+1+n)(1+1+n+n)+n = (2 + 2n)(2+2n)+n = 4n^2 + 9n + 4.

For the following loop, I find a time complexity of 1 (for int k = 0) + n + 1 (for i < n) + n (for k++) + 5n (for the five simple statements). This is 1+n+1+n+5n = 7n+2. For the next 25 simple statements, I find they have a time complexity of 25.

So the total time complexity is 4n^2 + 8n + 4 + 5n + 2 + 25 = 4n^2 + 16n + 31, however, my book says the time complexity is n^2 + 5n + 25.

What have I done wrong?

Edit: It is now apparent that the book is telling the time complexity of only the simple statements. I suppose now my question is this (as it was in the title): What is the time complexity of the algorithm?


回答1:


Your book is counting only the number of SimpleStatements executed.



来源:https://stackoverflow.com/questions/12851857/what-is-the-time-complexity-of-the-following-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!