classSolution: defmyPow(self, x: float, n: int) -> float: if n == 1: return x if n == -1: return1/x ifnot n: return1 if n < 0: res = 1/x for i in range(abs(n)-1): res = res*(1/x) else: res = x for i in range(abs(n)-1): res = res*x return res
第二种方法:分治(递归) ,时间复杂度O(logn)
1 2 3 4 5 6 7 8 9
classSolution: defmyPow(self, x: float, n: int) -> float: if n == 0: return1 if n < 0: return1 / self.myPow(x, -n) if n % 2: return x * self.myPow(x, n - 1) return self.myPow(x * x, n / 2)
稍微改成下面这样容易理解一些
1 2 3 4 5 6 7 8 9 10
classSolution: defmyPow(self, x: float, n: int) -> float: ifnot n: return1 if n < 0: return1/self.myPow(x, -n) if n & 1: return self.myPow(x, n - 1) * x res = self.myPow(x, n>>1) return res*res
第二种方法:循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defmyPow(self, x: float, n: int) -> float: if n < 0: x = 1 / x n = -n ans = 1 while n: # n&1 是与运算,用来求奇偶,效果与 n%2 一样 if n & 1: ans *= x x = x * x # n>>=1 是位运算,右移一位,效果与 n//=2 一样 n >>= 1 return ans
classSolution: defmajorityElement(self, nums: List[int]) -> int: for i in range(len(nums)): count = 1 for j in range(i+1, len(nums)): if nums[i] == nums[j]: count += 1 if count > len(nums) / 2: return nums[i]
第二种方法:哈希表记录每个元素出现次数,发现出现超过n/2的就是众数,时间复杂度O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defmajorityElement(self, nums: List[int]) -> int: leng = len(nums) if leng == 1: return nums[0] dic = {} for i in nums: if i in dic: dic[i] += 1 if dic[i] >= leng / 2: return i else: dic[i] = 1