当前位置: 移动技术网 > IT编程>脚本编程>Python > 169. Majority Element:Python

169. Majority Element:Python

2018年01月30日  | 移动技术网IT编程  | 我要评论

cruzerthebruzer,战场2011之王者无敌,湖北经视节目预告

169. Majority Element

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.

思路:

将列表中的数值进行一个出现次数的统计,然后判断出现最多次数的元素次数是否满足条件,是则输出。(这里用了2个for循环,效率不是很高,提交时速度只打败了50%不到的其他提交者,还有很大改进的余地)

代码:

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = {}
        for i in range(len(nums)):
            if nums[i] in dic:
                dic[nums[i]] += 1
            else:
                dic[nums[i]] = 1

        HighValue = 0
        HighKey = None
        for each in dic:
            if dic[each] > HighValue:
                HighValue = dic[each]
                HighKey = each
        if HighValue>len(nums)//2:
            return HighKey

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网