1:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
return 1.0/self.myPow(x, -n)
elif n==0:
return 1
elif n == 1:
return x
elif n%2 == 1:
return self.myPow(x, n//2) * self.myPow(x, n//2) * x
else:
return self.myPow(x, n//2) * self.myPow(x, n//2)
2:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n==0:
return 1
elif n==1:
return x
elif n < 0:
return 1 / self.myPow(x, -n)
elif n%2 == 1:
return x * self.myPow(x, n-1)
else:
return self.myPow(x*x, n//2)
I implemented poewr functions in two different ways.
I was expecting the time complexity to be the same, but when trying on leetcode, 1) timed out and failed for some examples, but 2) succeeded.
Is there a reason why that was the case? I thought time complexity would be the same for both.
Any help would be greatly appreciated. Thanks.