LeetCode題解(1441):用棧操作構建數組(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(N)O(N) O(N)O(N) 40ms (66.32%)
Ans 2 (Python) O(N)O(N) O(N)O(N) 36ms (86.88%)
Ans 3 (Python) O(T)O(T) : T爲target長度 O(1)O(1) 40ms (66.32%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(情景模擬):

def buildArray(self, target: List[int], n: int) -> List[str]:
    source = [i for i in range(1, n + 1)]
    ans = []
    while target and source:
        if target[0] == source[0]:
            target.pop(0)
            source.pop(0)
            ans.append("Push")
        else:
            source.pop(0)
            ans.append("Push")
            ans.append("Pop")
    return ans

解法二(雙指針情景模擬):

def buildArray(self, target: List[int], n: int) -> List[str]:
    source = [i for i in range(1, n + 1)]
    idx1 = 0
    idx2 = 0
    ans = []
    while idx1 < len(target) and idx2 < len(source):
        if target[idx1] == source[idx2]:
            idx1 += 1
            idx2 += 1
            ans.append("Push")
        else:
            idx2 += 1
            ans.append("Push")
            ans.append("Pop")
    return ans

解法三:

def buildArray(self, target: List[int], n: int) -> List[str]:
    ans = []
    last = 0
    for t in target:
        ans += ["Push", "Pop"] * (t - last - 1) + ["Push"]
        last = t
    return ans
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章