【发布时间】:2020-11-12 09:54:40
【问题描述】:
所以我写了这段代码,我想降低它的时间复杂度,但不知道怎么做,那么写一个更有效的算法的最好方法是什么,这样我就可以降低时间复杂度,代码首先从每个元素中减去它后面的小数字例如如果数组是[1, 5, 6, 3, 2],那么结果是[1, 2, 3, 1, 2]。
# an array with numbers
arr = [1, 5, 6, 3, 2]
# outer loop picks all element one by one
for i in range(0, len(arr), 1):
Next = arr[i]
# inner loop looks for the next smaller element
for j in range(i + 1, len(arr), 1):
if arr[i] > arr[j]:
# if the condition is true, the element will be subtracted form the next smaller element
# if there was no next smaller element, the element will kept without change
Next = arr[i] - arr[j]
break
print(Next)
【问题讨论】:
-
你能在问题中加入一行来说明整个代码的作用吗?
-
[1, 5, 6, 3, 2]的预期输出是什么? -
我编辑它以解释代码的作用@TheScientificMethod
-
我编辑它以解释代码的作用@AbhayAravinda
-
我看到你今天做了一个编辑,彻底改变了这个问题。请不要那样做。如果您有新问题,请提出新问题,但不要完全改变问题,因为这会使所有答案(及其背后的努力)看起来很愚蠢。注意:我回滚了你今天所做的重大改变。请点击“”并从那里开始。
标签: arrays algorithm loops element