码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】求众数

时间:2018-05-04 18:27:15      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:ret   color   众数   并且   solution   lse   obj   次数   +=   

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ? 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

 

【LeetCode】求众数

标签:ret   color   众数   并且   solution   lse   obj   次数   +=   

原文地址:https://www.cnblogs.com/dreamyu/p/8991563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!