欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

169. Majority Element:Python

程序员文章站 2022-07-25 15:24:11
169. Majority Element Given an array of size n, find the majority element. The majority e...

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