简体   繁体   English

具有二进制搜索的函数的时间复杂度和空间复杂度

[英]time complexity and space complexity of a function with binary search

I wrote the following function in Java ; 我用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;
}

I'm trying to figure out the time complexity and space complexity of this function. 我试图弄清楚此函数的时间复杂度和空间复杂度。 I know that the time complexity of binarySearch is O(logn) and space complexity of this function is O(1) . 我知道binarySearch的时间复杂度为O(logn) ,此函数的空间复杂度为O(1) With this information, I tried to calculate those things from of foo function. 有了这些信息,我试图通过foo函数来计算那些东西。 I think that the time complexity of foo is O((logn)^2) and space complexity is O(1) but I am not sure about it. 我认为foo的时间复杂度为O((logn)^2) ,空间复杂度为O(1)但我不确定。 What is the best method to calculate those things? 计算这些东西的最佳方法是什么?

Let's analyze a simplified while loop without the binarySearch() call: 让我们分析一个没有binarySearch()调用的简化的while循环:

while(num1 < n) {
    num1 = 2 * num1;
}

How many steps does this take as a function of n ? 作为n的函数,这需要多少步?

Once you answer this question, the key to a final solution is to realize that the complexity of a while loop multiplies by the complexity of its body. 一旦回答了这个问题,最终解决方案的关键就是要认识到while循环的复杂性乘以它主体的复杂性。 This means that the final answer is the answer to the above question time log n . 这意味着最终答案是上述问题时间log n的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM