LeetCode--Majority Element(出现次数最多的元素)Python

来源:互联网 发布:csp是什么软件 编辑:程序博客网 时间:2024/06/05 00:33

题目:

给定一个数组,长度为n,求出出现次数>=下取整(n/2)的元素。

解题思路:

考虑使用哈希表存储各个元素出现的次数,只用遍历一遍数组即可,复杂度为O(n)

代码(Python):

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

阅读全文
0 0
原创粉丝点击