leetcode算法题基础(十六)分治法(二)169. 多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        def help(low,high):
            if low == high:
                return nums[low]
            mid = (high-low)//2 + low
            left = help(low,mid)
            right = help(mid+1,high)
            if left == right:
                left
            left_count = sum(1 for i in range(low,high+1) if nums[i]==left)
            right_count = sum(1 for i in range(low,high+1) if nums[i]==right)
            return left if left_count > right_count else right
        return help(0,len(nums)-1)

本文来自博客园,作者:秋华,转载请注明原文链接:https://www.cnblogs.com/qiu-hua/p/13998847.html

原文地址:https://www.cnblogs.com/qiu-hua/p/13998847.html