[英]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.