![](/img/trans.png)
[英]What is the Big-O Time complexity of this recursive call with a for-loop
[英]Big-O Notation of a for-loop with an conditional inner loop
我試圖了解這個程序的時間復雜度,以及為什么。 我已經對我的想法做了一些筆記,但我不確定我是否理解正確。
public static int countSteps(int n) {
int pow = 2; // O(1)
int steps = 0; // O(1)
for (int i = 0; i < n; i++) { // O(n)
if (i == pow) { // O(1)
pow *= 2; // O(1)
for (int j = 0; j < n; j++) { // O(n)
steps++; // O(1)
}
}
else {
steps++; // O(1)
}
}
return steps; // O(1)
}
每次觸發 if 語句時,內部循環都會花費大量時間迭代 n,這會影響時間復雜度還是它仍然是常數?
外循環意味着它至少是 O(n)。 只有當i
是 2 的冪時,內部循環才會運行,所以它是 O(n*log n)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.