Python 第一个代码O(n)和第二个代码O(n^2)的复杂度是多少? 第一个代码: def最大利润更高效(列表): “”“计算特定股票的最大利润”“” 销售日期=0 购买日期=0 对于范围内的i(len(列表)): 如果列表[i]>列表[出售日期]: 销售日期=i 对于范围内的j(len(列表)): 如果列表[j]列表[出售日期]: 销售日期=i 如果我
第一个代码的复杂性是O(n),正如您所猜测的那样。Python 第一个代码O(n)和第二个代码O(n^2)的复杂度是多少? 第一个代码: def最大利润更高效(列表): “”“计算特定股票的最大利润”“” 销售日期=0 购买日期=0 对于范围内的i(len(列表)): 如果列表[i]>列表[出售日期]: 销售日期=i 对于范围内的j(len(列表)): 如果列表[j]列表[出售日期]: 销售日期=i 如果我,python,algorithm,complexity-theory,Python,Algorithm,Complexity Theory,第一个代码的复杂性是O(n),正如您所猜测的那样。 但是第二个代码的复杂度也是O(n)。即使在第二个代码中有一个嵌套的循环,由于j的值在循环外仅被设置为0一次,因此时间复杂度仅为O(n) 关于这个问题,你的推理是什么?另一种理解方法是:j上的循环在i上的循环退出之前只运行一次,如果i==len(list):。 def Maximum__profit_more_efficient(list): """compute the maximum_profit of specific stock"
但是第二个代码的复杂度也是O(n)。即使在第二个代码中有一个嵌套的循环,由于j的值在循环外仅被设置为0一次,因此时间复杂度仅为O(n) 关于这个问题,你的推理是什么?另一种理解方法是:
j
上的循环在i
上的循环退出之前只运行一次,如果i==len(list):
。
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])