简体   繁体   English

就大 O 而言,给定 function 的时间复杂度应该是多少?

[英]What should be the time complexity of the given function in terms of Big O?

int find_peak (int n, int A []) {
    int left, right, lmid, rmid;
    left = 0;
    right = n - 1;
    while (left + 3 <= right) {
        lmid = (2 * left + right) / 3;
        rmid = (left + 2 * right) / 3;
        if (A[lmid] <= A[rmid])
            left = lmid;
        else
            right = rmid;
    }
    int x = left;
    for (int i = left + 1; i <= right; i ++)
        if (A[i] > A[x])
            x = i;
    return A[x];
}

I was trying to solve this function for its BigO notation, but I am very confused about it.我试图解决这个 function 的 BigO 表示法,但我对此很困惑。 Is it O(log n) or something else?是 O(log n) 还是别的什么? I can somewhat solve it in my head but I can't do it on properly.我可以在脑海中解决它,但我不能正确地做到这一点。

Yes, the loop is cut roughly in half at each iteration是的,循环在每次迭代时大致减半

lmid = (2 * left + right) / 3;
rmid = (left + 2 * right) / 3;
if (A[lmid] <= A[rmid])
    left = lmid;
else
    right = rmid;

To be precise it's log 1.5 (n) , because the actual length right-left decreases only by 1 / 3 , not halving the iterations.准确地说,它是log 1.5 (n) ,因为实际right-left长度只减少了1 / 3 ,而不是将迭代减半。 The complexity is still O(log(n))复杂度仍然是O(log(n))

You can try it here https://onlinegdb.com/rkI5gn3Xd你可以在这里试试 https://onlinegdb.com/rkI5gn3Xd


Thanks to chqrlie for prompting me to give a more detailed answer感谢 chqrlie 提示我给出更详细的答案

The complexity of the above code should be O(log3n) ie.. logn base 3 .上述代码的复杂度应该是O(log3n)即.. logn base 3 because in the while loop the value of rmid always comes out as greater than lmid .So, for a given value of right ie.. n , the value of left will be reduced by a multiple of 1/3 at each iteration.因为在while 循环rmid的值总是大于lmid 。所以,对于给定的 right 值,即 .. n ,每次迭代时 left 的值将减少 1/3 的倍数。

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

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