【LeetCode】求众数

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

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

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) < 2:
            return nums[0]
        target = len(nums) / 2
        num_dic = {}
        for i in nums:
            if i in num_dic.keys():
                num_dic[i] += 1
            else:
                 num_dic[i] = 1
            if num_dic[i] > target:
                 return i
原文地址:https://www.cnblogs.com/dreamyu/p/8991563.html