简体   繁体   中英

Can someone help me figure out the time complexity of my Algorithm?

Example ArrayOne input: [-1, 5, 10, 20, 28, 3]

Example ArrayTwo input: [26, 134, 135, 15, 17]

My guess is it is O(n^2 + m^2) where n is the length of ArrayOne and m is the length of ArrayTwo?

在此处输入图片说明

Assuming len(arrayOne) = n and len(arrayTwo) = m

i = 0 and j = 0

Starting from the beginning, you have an outer while loop that is not immediately obvious how long it will run.

Inside the while loop you do some constant work, then check if j == m . This is not true, so j is incremented m times.

Now that j == m , you increment i and set j = -1 . This means that j will again increment m times. i increments and j resets.

j will reset n number of times.

So the inner loop here can be represented by m . And outer loop by n .

Therefore this algorithm has the runtime complexity of O(n * m)

Why oh why isn't this code just written as:

minDiff = float("inf")
for value1 in arrayOne:
    for value2 in arrayTwo:
        minDiff = min(minDiff, abs(value1 - value2))

It feels like this code is going out of its way to hide the fact that it's a pair of nested iterations and its time would have been obvious.

Which also means that it could be written as one line in Python:

minDiff = min(abs(value1 - value2) for value1 in arrayOne for value2 in arrayTwo)

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