今天,我和我的同事就一个特定的代码片段发生了一场小争论。代码看起来像这样。至少,他想象中是这样的。
for(int i = 0; i < n; i++) {
// Some operations here
}
for (int i = 0; i < m; i++) { // m is always small
// Some more operations here
}
Run Code Online (Sandbox Code Playgroud)
他希望我删除第二个循环,因为它会导致性能问题。
但是,我确信由于这里没有任何嵌套循环,因此无论我放置多少个顺序循环(我们只有 2 个),复杂性始终为O(n) 。
他的论点是,如果n是 1,000,000 并且循环需要 5 秒,我的代码将需要 10 秒,因为它有 2 个 for 循环。听到这句话后我很困惑。
我从 DSA 课程中记得的是,我们在计算 Big Oh 时忽略了这些常数。
我在这里缺少什么?
algorithm performance complexity-theory loops time-complexity