[英]Calculating time complexity of this algorithm
所以我在 Leetcode 上做這個問題,給定二叉樹的中序和前序遍歷,我們必須構建樹。 所以我編寫了代碼,並且解決方案正在運行,但是在計算解決方案的時間復雜度時我有點卡住了。 有人可以提供計算它的見解嗎? 任何輸入表示贊賞。 這是代碼:
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def construct(preord, inord, noted):
if preord == []:
return
root = TreeNode(preord[0])
noted.add(preord[0])
index = inord.index(preord.pop(0))
for i in inord[index::-1]:
if preord != [] and i == preord[0]:
root.left = construct(preord, inord, noted)
for i in inord[index + 1:]:
if i in noted:
break
if preord != [] and i == preord[0]:
root.right = construct(preord, inord, noted)
return root
visit = set()
root = construct(preorder, inorder, visit)
return root
變量聲明和條件具有相同的時間復雜度:
O(1)
This means constant time
取決於您擁有的數據量的循環或其他語句:
O(N)
如果您有依賴於數據的嵌套循環或再次語句:
O(n^k)
K being the number of nested levels you have.
這些不是唯一的,這是一個有用的鏈接,您可以在其中查看所有內容
https://www.bigocheatsheet.com/
根據您循環或檢查時間增加或減少的元素數量。 當我們談論時間復雜度時,我們需要始終將自己置於最壞的情況下。
假設您有 1000 個數字,並且您想檢查是否有 5 個,例如,您需要遍歷所有數字並檢查。
在最壞的情況下,您的程序可能需要檢查所有這些,這就是為什么循環是 O(n),n 是您的 1000 個數字。
回到你的程序,你沒有任何嵌套循環,但你有一些 for 循環,所以你的算法的大 O 是 O(n)。
您不需要計算 if 或任何其他少於 O(n) 的語句。
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def construct(preord, inord, noted):
if preord == []:
return
root = TreeNode(preord[0]) //O(1) <--------------------
noted.add(preord[0])
index = inord.index(preord.pop(0))
for i in inord[index::-1]: //O(n) <-------------
if preord != [] and i == preord[0]:
root.left = construct(preord, inord, noted)
for i in inord[index + 1:]:
if i in noted: //O(1) <---------------
break
if preord != [] and i == preord[0]:
root.right = construct(preord, inord, noted)
return root
visit = set()
root = construct(preorder, inorder, visit)
return root
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.