简体   繁体   中英

What is the complexity of this algorithm (search twice integer equals in an array)

I have a question, what is the complexity of this alogirthm ?

def search(t):
    i = 0;
    find = False
    while (not(find) and i < len(t)) :
        j = i + 1
        while (not(find) and j < len(t)) :
            if (t[j] == t[i]) :
                find = True
            j += 1
        i += 1
    return find

Thanks

Assuming t is a list, it's quadratic ( O(n^2) , where n is the length of the list).

You know it is because it iterates through t (first while loop), and in each of these iterations, it iterates through t again. Which means it iterates through len(t) elements, len(t) times. Therefore, O(len(t)**2) .

You can bring the complexity of that algorithm down to O(len(t)) and exactly one line of code by using the appropriate data structure:

def search(t):
    return (len(set(t)) != len(t))

For more info about how sets work, see https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset

The best case complexity is O(1), as the search may succeed immediately.

The worst case complexity is O(N²), achieved in case the search fails (there are (N-1)+(N-2)+...+2+1 comparisons made, ie N(N-1)/2 in total).

The average case can be estimated as follows: assuming that the array contains K entries that are not unique and are spread uniformly, the first of these is located after N/K elements on average, so the outer loop will run N/K times, with a cost of (N-1)+(N-2)+....+(NN/K) comparisons. In the last iteration of the outer loop, the inner loop will run about 2N/K times.

Roughly, the expected time is O(N²/K).

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