LeetCode 169 Majority Element (Python)

Posted by 小明MaxMing on May 6, 2020

题目

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

解题思路

将数组转换成计数器,遍历计数器中的每一项,找出现次数大于n/2的数

代码

from collections import Counter
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        ct = Counter(nums)
        l = len(nums) / 2
        for key, value in ct.items():
            if value >= l:
                return key

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅