要将算法的时间复杂度从O(n ^ 2)降到O(n),可以使用以下方法:
def biggest_decrease_list(arr): decrease_list = [arr[0]] last_index = 0
for i in range(1, len(arr)):
if arr[i] < decrease_list[-1]:
decrease_list.append(arr[i])
last_index += 1
else:
index = find_index(decrease_list, arr[i])
decrease_list[index] = arr[i]
return decrease_list
def find_index(arr, x): left = 0 right = len(arr) - 1 index = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] >= x:
index = mid
left = mid + 1
else:
right = mid - 1
return index + 1
arr = [3, 2, 6, 4, 5, 1] print(biggest_decrease_list(arr)) # [6, 5, 1]