2个嵌套while循环的运行时间

发布于 2024-10-15 22:55:38 字数 390 浏览 4 评论 0原文

我还有一个关于循环的问题。我知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水水月牙 2024-10-22 22:55:38

在这种情况下,它们看起来并不像嵌套的。有 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.

各自安好 2024-10-22 22:55:38

正如您所说,嵌套 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).

飘过的浮云 2024-10-22 22:55:38
while (array1 isn't empty){
     while (array2 isn't empty){
         //code goes here
     }
}

如果第一个数组有 n 个元素,第二个数组有 m 个元素,则运行时间为 O( n * m )

在 n 和 m 相同的特殊情况下,则为 O( n * n )

while (array1 isn't empty){
//code
}

while (array2 isn't empty){
//code
}

在这种情况下,运行时间是 O(n) + O(m),如果 n 大于或等于 m,则为 O(n);如果 m 大于或等于 n,则为 O(m)。

while (array1 isn't empty){
     while (array2 isn't empty){
         //code goes here
     }
}

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 )

while (array1 isn't empty){
//code
}

while (array2 isn't empty){
//code
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文