簡體   English   中英

我怎樣才能更有效地編寫這個算法? 以降低時間復雜度的方式?

[英]how can i write this algorithm more efficiently ? in a way that reduce time complexity?

所以我寫了這段代碼,我想降低它的時間復雜度,但不知道怎么做,那么寫一個更有效的算法的最好方法是什么,這樣我就可以降低時間復雜度,代碼從每個元素中減去后面的第一個小數字例如,如果數組是[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)

實際上,您的解決方案具有O(n²)時間復雜度。 你可以改進它。

從列表的末尾開始並向后走。

這樣做時,當檢查的列表值不小於當前堆棧頂部的值時,將其壓入堆棧。 同時output的區別。

另一方面,當檢查的值小於堆棧頂部的值時,則彈出堆棧,直到輸入值上的值不再小於堆棧頂部的值,然后再次執行上一段中描述的。

這是該想法的實現:

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

調用這個 function 如下:

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

該算法具有線性時間復雜度: O(n) 盡管內部的while循環看起來對非線性時間復雜度很懷疑,但它仍然存在,因為給定的列表值最多只能在堆棧上/從堆棧中被推入和拉出一次

使用堆棧,其中堆棧上的每個項目都是一個元組: (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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM