2个嵌套while循环的运行时间
我还有一个关于循环的问题。我知道 2 个 for 循环的运行时间为 O(n^2),因为您迭代列表 n * n 次。
但是两个 while 循环呢?
While (array1 is not empty)
if(~~~)
do ~~~
else(~~~)
do ~~~
while (array2 is not empty)
if(~~~)
do ~~~
else(~~~)
do ~~~
所以一个 while 循环嵌套在另一个 while 循环内。由于我们迭代第一个循环 n 次和第二个循环 n 次,这是否也会使运行时间 n^2 ?任何帮助将不胜感激。
谢谢!
I had another question regarding loops. I know 2 for loops make the run time O(n^2) since you iterate through the list n * n times.
But what about two while loops?
While (array1 is not empty)
if(~~~)
do ~~~
else(~~~)
do ~~~
while (array2 is not empty)
if(~~~)
do ~~~
else(~~~)
do ~~~
so a while loop is nested inside another while loop. Does this make the run time n^2 also since we iterate though the first loop n times and second loop n times? Any help would be apreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,它们看起来并不像嵌套的。有 2 个循环,由 if/else 分隔。在这种情况下,它将是 O(n)。
如果 while 循环是嵌套的并且基于输入大小,那么它确实是 O(n^2)。您使用的循环“类型”并不重要,重要的是您正在循环大小为 n 的输入。
In this case, it doesn't look like they are nested. There are 2 loops, separated by an if/else. In this case, it would be O(n).
If the while loops were nested and based on input size, it would indeed be O(n^2). It's not important what 'type' of loop you are using, but rather the fact that you're looping over the input of size n.
正如您所说,嵌套 for 循环的运行时间为 O(n²)。用于确定其中两个序列的运行速度的符号是 O(2n²)。运行两个 while 循环各 n 次的表示法是 O(2n)。
A nested for loop runs at O(n²), as you said. The notation for determining how fast two of these in sequence will run is O(2n²). The notation for running two while loops n times each is O(2n).
如果第一个数组有 n 个元素,第二个数组有 m 个元素,则运行时间为 O( n * m )
在 n 和 m 相同的特殊情况下,则为 O( n * n )
在这种情况下,运行时间是 O(n) + O(m),如果 n 大于或等于 m,则为 O(n);如果 m 大于或等于 n,则为 O(m)。
If the first array has n elements and the 2nd array has m elements then the runtime is O( n * m )
In the special case where n and m are the same, then it is O( n * n )
In this case the runtime is O(n) + O(m) which is O(n) if n is greater than or equal to m and O(m) if m is greater than or equal to n.