169. 多数元素
class Solution:def majorityElement(self, nums, lo=0, hi=None):def majority_element_rec(lo, hi):# 对于只有一个元素的数组,其众数就是数组元素if lo == hi:return nums[lo]# 在切片的左右两部分上递归mid = (hi-lo)//2 + loleft = majority_element_rec(lo, mid)right = majority_element_rec(mid+1, hi)# 如果两部分的众数一致,则返回if left == right:return left# 否则对元素进行计数并返回众数left_count = sum(1 for i in range(lo, hi+1) if nums[i] == left)right_count = sum(1 for i in range(lo, hi+1) if nums[i] == right)return left if left_count > right_count else rightreturn majority_element_rec(0, len(nums)-1)参考链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
53. 最大子序列和
class Solution:def maxSubArray(self, nums: List[int]) -> int:n = len(nums)#递归终止条件if n == 1:return nums[0]else:#递归计算左半边最大子序和max_left = self.maxSubArray(nums[0:len(nums) // 2])#递归计算右半边最大子序和max_right = self.maxSubArray(nums[len(nums) // 2:len(nums)])#计算中间的最大子序和,从右到左计算左边的最大子序和,从左到右计算右边的最大子序和,再相加max_l = nums[len(nums) // 2 - 1]tmp = 0for i in range(len(nums) // 2 - 1, -1, -1):tmp += nums[i]max_l = max(tmp, max_l)max_r = nums[len(nums) // 2]tmp = 0for i in range(len(nums) // 2, len(nums)):tmp += nums[i]max_r = max(tmp, max_r)#返回三个中的最大值return max(max_right,max_left,max_l+max_r)参考链接:https://leetcode-cn.com/problems/maximum-subarray/solution/bao-li-qiu-jie-by-pandawakaka/
50. Pow(x, n)
class Solution:def myPow(self, x: float, n: int) -> float:# 处理特殊情况(x为0)if x == 0.0: return 0.0res = 1# 如果n为负数,先求处x的倒数和n的相反数if n < 0: x, n = 1 / x, -n# 快速幂法# 统一处理逻辑,用while循环计算幂函数while n:if n & 1: res *= xx *= xn >>= 1return res参考链接:https://leetcode-cn.com/problems/powx-n/solution/50-powx-n-kuai-su-mi-qing-xi-tu-jie-by-jyd/