简体   繁体   中英

What would be the worst case time complexity for this algorithm?

Here's the algorithm:

boolean findTripleA(int[] anArray) { 
    if (anArray.length <= 2) { 
        return false; 
    } 

    for (int i=0; i < anArray.length; i++) { 
        // check if anArray[i] occurs at least three times 
        // by counting how often it occurs in anArray 

        int count = 0; 

        for (int j = 0; j < anArray.length; j++) { 
            if (anArray[i] == anArray[j]) { 
                count++; 
            } 
        } 

        if (count >= 3) { 
            return true; 
        } 
    } 

    return false;
}

The algorithm is designed to determine whether an array contains at least one number that occurs three times or more in the array. My job is to figure out what would be the worst-case for this array, and its time complexity.

My thinking is that the worst case would be if the algorithm had two occurrences of every entry (with the extra entry being unique if the array has an odd number of elements). In this case, the if statement within for (int j = 0; j < anArray.length; j++) is always violated twice for each pass through the array, forcing the computation to be performed twice, but the algorithm doesn't actually terminate until it has checked every element. I was thinking that this would have a time complexity of O(n^2) .

Can anyone provide any insight into this one? Because I have a nagging suspicion that I'm incorrect, and if I am I'd like to figure out the correct answer and why it's correct.

最坏的情况是O(N ^ 2),当您找不到三元组时就会发生这种情况。

If we're talking about pure running time, then when the if-statement condition is true comes into play (and then you'd also have to worry about things like branch prediction), but

if (anArray[i] == anArray[j]) { 
    count++; 
}

takes O(1) time, whether the if-statement condition is true or not. So, for running time complexity , the whole function would take O(n 2 ). This would happen in any case where either there aren't 3 occurrences, or the first occurrence of an element appearing 3 or more times is near the end ('near the end' may not actually be so near, but let's leave that for another day).

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