【问题标题】:How to find runtime of algorithm in big-o如何在 big-o 中找到算法的运行时间
【发布时间】:2016-05-12 03:02:43
【问题描述】:
public void do() {
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            // do something

    for (int i = 1; i < rows - 1; i += 2)
        for (int j = 1; j < columns - 1; j += 2) {
            // do something

    for (int i =  50; i > 0; i--)
        // do something

    for (int i = 1; i < rows - 1; i++)
        for (int j = 1; j < columns - 1; j++)
            // do something
}

在这种情况下,行和列将相等:

rows = (size * 10) + 1;
columns = rows + 10;

其中size (n) 是 1、2、4 或 8。

由于rows 和columns 变量的大小会随着大小而增加,并且每个循环都会遍历行,然后循环内的列,我可以说这个函数将在 O(n ^2)?

我对算法的整体复杂性相当陌生,希望对此有所了解。非常感谢。

【问题讨论】:

  • 否,因为n 未定义。
  • 对不起,我定义了。大小不是 n 吗?
  • 你可以关注这个question

标签: java algorithm performance runtime big-o


【解决方案1】:

直接回答您的代码: What is the Big-O of a nested loop, where number of iterations in the inner loop is determined by the current iteration of the outer loop?

N是一个循环,所以两个嵌套= N^2,等等。如果嵌套循环中有2条指令,实际上是2N^2,但是乘以2是无用的,所以N^2无论如何。

【讨论】:

  • 干杯,您所附的答案也有帮助。
  • 您应该将问题标记为重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 2021-04-30
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多