題目:原題鏈接(簡單)
解法 | 時間複雜度 | 空間複雜度 | 執行用時 |
---|---|---|---|
Ans 1 (Python) | 40ms (66.32%) | ||
Ans 2 (Python) | 36ms (86.88%) | ||
Ans 3 (Python) | : T爲target長度 | 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