[英]Finding the time complexity of this method
我試圖弄清楚這段代碼的時間復雜度。
我對這些部分的最后結論是,“ while”部分的O(logn)外部for循環必須小於100,因此其O(1)和內部for循環為O(logn),因此我認為此處的時間復雜度在最壞的情況下是O(logn),但我不確定。
public void foo (int n, int m) {
int i = m;
while (i > 100) {
i = i/3;
}
for (int k=i ; k>=0; k--) {
for (int j=1; j<n; j*=2) {
System.out.print(k + "\t" + j);
}
System.out.println();
}
}
讓我們逐步破壞您的代碼:
第一個循環,即
while (i > 100)
i = i/3;
運行O(logm)次。
for (int k=i ; k>=0; k--) {
for (int j=1; j<n; j*=2) {
System.out.print(k + "\t" + j);
} //end inner for loop
System.out.println();
}
外循環最多可以運行100次,而內循環即
for (int j=1; j<n; j*=2) {
System.out.print(k + "\t" + j);
} //end inner for loop
執行登錄時間。
for循環的總時間復雜度= 100logn->忽略常量-> logn
因此,復雜度為O(log(m))+ O(log(n))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.