这是二次O(n ^ 2):
x = [(i,xyz_list.count(i)) for i in xyz_set]
xyz_list.count(i)) # 0(n) operation
对于xyz_set中的每个i,你做一个0(n)xyz_list.count(i)
你可以使用double for循环编写它,这将使它更明显:
res = []
for i in xyz_set: # 0(n)
count = 0
for j in xyz_list: # 0(n)
if i == j: # constant operation 0(1)
count += 1 # constant operation 0(1)
res.append(count) # constant operation 0(1)
通常当你看到一个双循环时,复杂性将是二次的,除非你正在处理一些常数,例如我们只想检查xyz_list的前7个元素,然后运行时间将是0(n)假设我们正在做内在的同样不断的工作:
sec = 7
res = []
for i in xyz_set:
count = 0
for j in xyz_list[:sec]:
......