[英]Time complexity of this nested for loop
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++;
}
}
}
我必須計算這個 function 的時間復雜度,我最初認為它是 ~n*n-1 但我很確定這實際上是錯誤的。 誰能解釋這段代碼的時間復雜度是多少?
每個迭代 (tiles.length*tiles.length) 次有 2 個 for 循環。 所以它是:
比較次數:
第一組比較(i=0):tiles.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 )
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)
希望能有所幫助。
查看下面的資源以獲得更深入的解釋。
資源:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.