今天做leetcode第7題關於數字倒序的問題,分別使用如下程序:(72ms)
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#maxNum = 2**31-1
#minNum = -1*2**31
i = 1
if(x<0):
i,x = -1,abs(x)
x_s = str(x)
x_s = i*int(x_s[::-1])
if x_s >2147483647 or x_s < -2147483648:
return 0
return x_s

而使用方法2:(112ms)
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#maxNum = 2**31-1
#minNum = -1*2**31
i = 1
if(x<0):
i,x = -1,abs(x)
x_s = str(x)
x_s = i*int(x_s[::-1])
return 0 if x_s >2147483647 or x_s < -2147483648 else x_s

在做一下改進:(76ms)
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#maxNum = 2**31-1
#minNum = -1*2**31
i = 1
if(x<0):
i,x = -1,abs(x)
x_s = str(x)
x_s = i*int(x_s[::-1])
return x_s if x_s <= 2147483647 and x_s >= -2147483648 else 0
#return 0 if x_s >2147483647 or x_s < -2147483648 else x_s

對比三種方法,可以看到,其實簡簡單單的一個if else,也有需要我們仔細考慮的:
第2種方法用時大,是因為用例大多數都是else中的內容,這樣的話,大部分用例都執行完if又執行的else,這樣的話,有一個if 為False之后的跳轉過程,導致開銷變大。
對於第3種方法,比第二種方法效率高的原因是:大部分用例都只執行到if階段
而第1種方法和第3種方法對比,在於第1種方法使用的是 or ,對於 or 判決,如果第一個為真就滿足了,可以縮小一些開銷吧;
而第1種方法和第2種方法比,同樣也是因為第2種方法else的跳轉導致的。
總結就是:使用if-return-return 比 if-else-return更有效率一些。
參考:‘
