具体算法思想参见
team-learning-program/LeetCodeClassification/1.分治.md
下面是对上面链接中的各个leetcode题给出的代码测试版本(注意类名称都由Solution改为相互不同名称):
# 169多数元素
class MajorityElement(object):def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""# 【不断切分的终止条件】if not nums:return Noneif len(nums) == 1:return nums[0]# 【准备数据,并将大问题拆分为小问题】left = self.majorityElement(nums[:len(nums)//2])right = self.majorityElement(nums[len(nums)//2:])# 【处理子问题,得到子结果】# 【对子结果进行合并 得到最终结果】if left == right:return leftif nums.count(left) > nums.count(right):return leftelse:return right# 53. 最大子序和
class MaxSum(object):def maxSubArray(self, nums):""":type nums: List[int]:rtype: int"""# 【确定不断切分的终止条件】n = len(nums)if n == 1:return nums[0]# 【准备数据,并将大问题拆分为小的问题】left = self.maxSubArray(nums[:len(nums) // 2])right = self.maxSubArray(nums[len(nums) // 2:])# 【处理小问题,得到子结果】# 从右到左计算左边的最大子序和max_l = nums[len(nums) // 2 - 1] # max_l为该数组的最右边的元素tmp = 0 # tmp用来记录连续子数组的和for 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(left, right, max_l + max_r)# 50. Pow(x, n)
class PowNum(object):def myPow(self, x, n):""":type x: float:type n: int:rtype: float"""# 处理n为负的情况if n < 0 :x = 1/xn = -n# 【确定不断切分的终止条件】if n == 0:return 1# 【准备数据,并将大问题拆分为小的问题】if n % 2 == 1:# 【处理小问题,得到子结果】p = x * self.myPow(x, n-1)# 【对子结果进行合并 得到最终结果】return preturn self.myPow(x*x, n/2)# 在mian中测试各个类
if __name__ == "__main__":# test 169 majority elementmajorityNum = MajorityElement()nums1 = [-1, 2, 1, 1, 1, 2, 0]mj1 = majorityNum.majorityElement(nums1)print(mj1)# test 53 max sub-summaxsum = MaxSum()nums2 = [-2, 1, -3, 4, -1, 2, 1, -5, 4]msm = maxsum.maxSubArray(nums2)print(msm)# test 50 powpownum = PowNum()ps = pownum.myPow(32, 5)print(ps)
测试结果