您已正确确定 while 循环是迭代n/2
次数。其中包含的外部循环在后续迭代for
中执行j = 1, 2, ... i
,其中i
设置为len(lst)
, len(lst) - 2
, ...。所以,外循环是针对, , ...,执行的。总的来说,这是外循环的迭代。虽然内部循环的执行次数不是恒定的,但它最多迭代,这是恒定的。因此,是此函数运行时的正确上限。1
while
for
j = 1, 2, ..., len(lst)
j = 1, 2, ..., len(lst) - 2
j = 1
O(n^2)
for
for
10**5
O(n^2)
这里有一个稍微不同的解释。我希望您同意以下代码在计算时间方面与您的代码等效:
def f3_simple(n):
i = n
condition = i>0
while condition:
r1 = range(i)
for j in r1:
r2 = range(j, 10**5)
for k in r2:
print(i)
i -= 2
condition = i>0
这是相同的代码,带有注释:
def f3_simple(n):
i = n # "length": O(1)
condition = i>0 # comparison: O(1)
while condition: # executed O(n) times per function call
r1 = range(i) # range(i): O(i)
for j in r1: # executed O(n) times per WHILE iteration
r2 = range(j, 10**5) # range(j, 10**5): O(10**5 - j) = O(1)
for k in r2: # executed O(1) times per OUTER FOR iteration
print(i) # print: O(1)
i -= 2 # decrement: O(1)
condition = i>0 # comparison: O(1)
因此,总运行时间确实是O(n^2)
.