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.