函数内函数的 Big-O 分析
我对 Big-O 在处理函数内的函数时(分析最坏情况时)如何工作感到困惑。例如,如果您有这样的情况:
for(int a = 0; a < n; a++)
{
*some function that runs in O(n*log(n))*
for(int b = 0; b < n; b++)
{
*do something in constant time*
}
}
整个块会在 O(n^2*log(n)) 中运行吗?因为在第一个 for 循环中,您有一个 O(n) 和一个 O(n*log( n)),所以 O(n*log(n)) 更大,因此我们取那个?或者是 O(n^3*log(n)) 因为外部 for 循环中有 O(n) 和 O(n*log(n)) ?
任何帮助表示赞赏!谢谢!
I'm confused about how Big-O works when dealing with functions within functions (when analyzing worst case). For example, what if you have something like:
for(int a = 0; a < n; a++)
{
*some function that runs in O(n*log(n))*
for(int b = 0; b < n; b++)
{
*do something in constant time*
}
}
Would this entire block run in O(n^2*log(n)), because within the first for loop, you have an O(n) and an O(n*log(n)), so O(n*log(n)) is greater, and therefore the one we take? Or is it O(n^3*log(n)) because you have an O(n) and an O(n*log(n)) within the outer for loop?
Any help is appreciated! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
因为您有
O(N lg N)
函数的O(N)
次迭代和O(N)
常数时间操作。O(N lg N) + O(N)
简化为O(N lg N)
因为O(N lg N) > O(N)。
It's
Because you have
O(N)
iterations of anO(N lg N)
function andO(N)
constant time operations. TheO(N lg N) + O(N)
simplifies toO(N lg N)
becauseO(N lg N) > O(N)
.计算此类复杂性时,您应该添加内联或顺序函数以及乘嵌套函数。
例如,这将是
O(n)
:但是当函数嵌套时,会增加它们的复杂性:
您的示例是一个组合 - 您在另一个函数中嵌套了一些顺序操作。
When calculating this type of complexity you should add inline or sequential functions and multiply nested functions.
For example, this would be
O(n)
:But when the functions are nested, multiply their complexity:
Your example is a combination - you've got some sequential operations nested inside another function.