【问题标题】:how can i write this algorithm more efficiently ? in a way that reduce time complexity?我怎样才能更有效地编写这个算法?以降低时间复杂度的方式?
【发布时间】: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


【解决方案1】:

确实,您的解决方案具有 O(n²) 时间复杂度。你可以改进一下。

从列表末尾开始往回走。

这样做时,将检查的列表值压入堆栈,当它不小于当前堆栈顶部的值时。同时输出差值。

另一方面,当检查的值小于堆栈顶部的值时,则弹出堆栈,直到输入值上的值不再小于该值在堆栈顶部,然后按照上一段所述再次执行。

这是该想法的实现:

def solve(arr):
    stack = [0]
    result = arr[:]
    # outer loop picks all element one by one
    for i in range(len(arr) - 1, -1, -1):
        val = arr[i]
        while val <= stack[-1]:
            stack.pop()
        result[i] = val - stack[-1]
        stack.append(val)
    return result

调用该函数如下:

arr = [1, 5, 6, 3, 2]
print (solve(arr))   # [1, 2, 3, 1, 2]

该算法具有线性时间复杂度:O(n)。尽管内部 while 循环看起来怀疑非线性时间复杂度,但它仍然是,因为给定的列表值最多只会在堆栈上/从堆栈中推送和拉出一次 p>

【讨论】:

  • 非常感谢。这很有帮助。
  • 注意数字
【解决方案2】:

使用堆栈,其中堆栈上的每个项目都是一个元组:(index, value)。当找到较小的值时,将项目从堆栈中弹出。然后将新元组推入堆栈。在伪代码中:

for each array element
   while the stack is not empty
      if the top stack_value is greater than the element_value
         pop the (index, stack_value) from the stack
         set arr[index] = stack_value - element_value
   push the tuple (index, element_value) onto the stack

在python中:

arr = [1, 5, 6, 3, 2]
stack = []
for i in range(len(arr)):
   while len(stack) and stack[-1][1] > arr[i]:
      index, value = stack.pop()
      arr[index] = value - arr[i]
   stack.append((i, arr[i]))
print arr    # [1, 2, 3, 1, 2]

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多