此嵌套for循环的时间复杂度

时间:2020-04-28 16:40:38

标签: java time-complexity

for (int i = 0; i < this.tiles.length * this.tiles.length; i++) {
        int row = i / this.tiles.length;
        int col = i % this.tiles.length;
        for (int j = i+1; j < this.tiles.length * this.tiles.length; j++) {
            int compareRow = j / this.tiles.length;
            int compareCol = j % this.tiles.length;
            if(this.tiles[compareRow][compareCol] < this.tiles[row][col]) {
                count++;
            }
        }
    }

我必须计算该函数的时间复杂度,我首先认为它是〜n * n-1,但是我敢肯定这实际上是错误的。谁能解释这段代码的时间复杂度是什么?

2 个答案:

答案 0 :(得分:0)

有2个for循环,每次迭代(tiles.length * tiles.length)次。就是这样:

比较次数:

  • 第一组比较(i = 0):tile.length 2

  • 第二组比较(i = 1):tiles.length 2 -1

  • 最后一组比较(i = tiles.length 2 -1):1

=((tiles.length 2 )+(tiles.length 2 -1)+(tiles.length 2 -2) ....... + 2 +1)

= O(tiles.length 3

答案 1 :(得分:0)

 for (int i = 0; i < this.tiles.length * this.tiles.length; i++) { //O(n)
        int row = i / this.tiles.length; 
        int col = i % this.tiles.length; 
        for (int j = i+1; j < this.tiles.length * this.tiles.length; j++) { //O(n^2) it's squared because there are two loops
            int compareRow = j / this.tiles.length; //n +
            int compareCol = j % this.tiles.length; //+ n
            if(this.tiles[compareRow][compareCol] < this.tiles[row][col]) {  //n
                count++; 
            }
        }
    }

O(n ^ 2 + n)== O(n ^ 2)

我被教导的方式是,对于每个循环,它都是O(n),所以嵌套循环自然是O(n ^ 2),并且在每个条件或操作下,n + n ..nth都是O (n ^ 2 + n)= O(n ^ 2)

希望有所帮助。

在下面的资源中查看更深入的解释。

资源: