【问题标题】:What would be the time complexity for using for and while loops together in a code?在代码中同时使用 for 和 while 循环的时间复杂度是多少?
【发布时间】:2022-01-03 08:47:27
【问题描述】:

我知道使用两个 for 循环的总和为 O(N^2)。 for循环和while循环是一样的吗?

这是一个代码sn-p

 for(int num : nums)
    {
        if(!set.contains(num-1))
        {
            int currNum = num;
            int currStreak = 1;
            
            while(set.contains(currNum+1))
            {
                currNum += 1;
                currStreak += 1;
            }
            longestStreak = Math.max(longestStreak, currStreak);
        }
    } 

【问题讨论】:

  • 您认为forwhile 有何不同?
  • 两个 for 循环不一定“总和”到 O(n^2),顺便说一下……

标签: java time-complexity


【解决方案1】:

正如德哈尔所写。两个 for 循环的复杂度并不总是 O(n^2)。

例如,对于以下代码:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n * n; j++) {
        //do something
    }
}

复杂度是O(n^3),因为代码执行了“做某事”n^3 次。

请注意,while 和 for 在技术上是相同的。 代码:

for (int i = 0; i < 100; i++) {
    //do something
}

可以翻译成:

int i = 0;
while(i < 100) {
    //do something
    i++;
}

所以在你的例子中:

假设 m 是最长的连胜。现在 while 循环内的代码最多运行 m 次。现在假设 n 是数字的数量。所以for循环中的代码运行了n次。

在 while 内部的代码中,每次 for lop 运行时都会运行 m 次,因此总共 m*n 次。所以复杂度是O(n*m)

如果set 的内容是nums,那么最长可能的连续长度将是长度为n。然后你可以说复杂度是O(n^2)

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多