Majority Element众数

Easy

给定序列长度为n,寻找它的众数。众数是在序列中出现n/2次以上的数。假设给定序列不空,众数一定存在

Solution:

方法一: 数数喽。需要借助别的package, 效率不高。

from collections import Counter
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = Counter(nums)
        count_values = count.values()
        return count.keys()[count_values.index(max(count_values))] 

方法二:借助字典

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = {}
        for num in nums:
            if num not in dic:
                dic[num]=1
            if dic[num] > len(nums)//2: return num
            else: dic[num]+=1

你可能感兴趣的:(Majority Element众数)