题目:
给定一个数组,长度为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