第一个代码的复杂度是O(n),第二个代码的复杂度是O(n^2)吗?
Is the complexity of the first code O(n), and the second code O(n ^2)?
第一个代码:
def Maximum__profit_more_efficient(list):
"""compute the maximum_profit of specific stock"""
selling_date = 0
buying_date = 0
for i in range(len(list)):
if list[i] > list[selling_date]:
selling_date = i
for j in range(len(list)):
if list[j] < list[buying_date] and j <= selling_date:
buying_date = j
elif j > selling_date:
break
print(list[selling_date] - list[buying_date])
第二个代码:
def brute_force(list):
"""compute the maximum_profit of specific stock, but with higher complexity"""
selling_date = 0
buying_date = 0
i = 0
j = 0
exit = False
while exit == False:
if list[i] > list[selling_date]:
selling_date = i
if i < len(list):
i = i + 1
if i == len(list):
while j < len(list):
if list[j] < list[buying_date] and j <= selling_date:
buying_date = j
j = j + 1
if j == len(list):
exit = True
print(list[selling_date] - list[buying_date])
如您所料,第一个代码的复杂度为 O(n)。
但是第二个代码的复杂度也是O(n)。即使在第二个代码中有一个嵌套循环,由于 j 的值仅在循环外设置一次为 0,时间复杂度仅为 O(n)。
第一个代码:
def Maximum__profit_more_efficient(list):
"""compute the maximum_profit of specific stock"""
selling_date = 0
buying_date = 0
for i in range(len(list)):
if list[i] > list[selling_date]:
selling_date = i
for j in range(len(list)):
if list[j] < list[buying_date] and j <= selling_date:
buying_date = j
elif j > selling_date:
break
print(list[selling_date] - list[buying_date])
第二个代码:
def brute_force(list):
"""compute the maximum_profit of specific stock, but with higher complexity"""
selling_date = 0
buying_date = 0
i = 0
j = 0
exit = False
while exit == False:
if list[i] > list[selling_date]:
selling_date = i
if i < len(list):
i = i + 1
if i == len(list):
while j < len(list):
if list[j] < list[buying_date] and j <= selling_date:
buying_date = j
j = j + 1
if j == len(list):
exit = True
print(list[selling_date] - list[buying_date])
如您所料,第一个代码的复杂度为 O(n)。 但是第二个代码的复杂度也是O(n)。即使在第二个代码中有一个嵌套循环,由于 j 的值仅在循环外设置一次为 0,时间复杂度仅为 O(n)。