[英]Time and space complexity of this function to print binary tree level by level
[英]time complexity and space complexity of a function with binary search
我用Java
編寫了以下函數;
int foo(int a[], int n) {
int num1 = 1, num2 = 1;
while(num1 < n) {
if (binarySearch(a,num1,num2) >= 0) {
return num2;
}
num1 = 2 * num1;
num2 = 2 * num2;
}
return 0;
}
我試圖弄清楚此函數的時間復雜度和空間復雜度。 我知道binarySearch
的時間復雜度為O(logn)
,此函數的空間復雜度為O(1)
。 有了這些信息,我試圖通過foo
函數來計算那些東西。 我認為foo
的時間復雜度為O((logn)^2)
,空間復雜度為O(1)
但我不確定。 計算這些東西的最佳方法是什么?
讓我們分析一個沒有binarySearch()
調用的簡化的while
循環:
while(num1 < n) {
num1 = 2 * num1;
}
作為n
的函數,這需要多少步?
一旦回答了這個問題,最終解決方案的關鍵就是要認識到while循環的復雜性乘以它主體的復雜性。 這意味着最終答案是上述問題時間log n
的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.