為什么只是以不同的順序或風格撰寫代碼會改變整體運行時?
例如:
為什么 is
result = "1"比 快result = "1" result?
更詳細的例子:
為這個 Leetcode 問題撰寫成功的程式后 -添加二進制
在這里,我有兩個相同的代碼片段,但有一個非常微妙的區別。
代碼 1
def addBinary(a, b):
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ""
carry = 0
for i in range(len(a)-1, -1, -1):
x = int(a[i])
y = int(b[i])
_sum = x y carry
if _sum == 3:
result = "1"
carry = 1
elif _sum == 2:
result = "0"
carry = 1
elif _sum == 1:
result = "1"
carry = 0
else:
result = "0"
carry = 0
if carry == 1:
result = "1"
return result[::-1]
代碼 2
def addBinary(a, b):
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ""
carry = 0
for i in range(len(a)-1, -1, -1):
x = int(a[i])
y = int(b[i])
_sum = x y carry
if _sum == 3:
result = "1" result
carry = 1
elif _sum == 2:
result = "0" result
carry = 1
elif _sum == 1:
result = "1" result
carry = 0
else:
result = "0" result
carry = 0
if carry == 1:
result = "1"
return result
CODE 1的運行時間是16 ms,而CODE 2的運行時間是47 ms。為什么?
uj5u.com熱心網友回復:
Adding characters to the end is optimised internally to reuse the same string (array of characters) in memory. Adding at the beginning requires creating a new string, with the position of each character shifted.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422155.html
標籤:
上一篇:一個頁面上有兩個表,我如何在谷歌表中使用importxml只匯入一個表
下一篇:二進制搜索
