简体   繁体   中英

Big-O of a while loop in Java

I was wondering what the Big-O of this code is

static boolean mysterious(int[] w) {
    int anz = w.length;
    int i = 0;
    int j = anz - 1;

    while (i < j) {
        if (w[i] != w[j]) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

I would say it's O(j) but I am not quite sure.

Thanks for your help!

i and j start pointing at either end of the array w and i moves forward while j moves back. At each step, we compare the elements referred to by i and j . So, it is O(w.length) asymptotically

We can speak here of the best/worst case performance. The best case performance is O(1) , and would occur if the first and last elements of the array input were not equal.

In the worst case, there would be N/2 iterations of the while loop. This would occur if the number array did not contain any sub array about the middle element which were not a palindrome. So in the worst case, the function is O(N) , where N is the length of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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