Majority Element
1. Hashmap
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hashmap = collections.Counter(nums)
for i in hashmap:
if hashmap[i] > len(nums)/2:
return i2. 排序:将数组排序,因为多数的元素超过一半,因此排序后中间的元素必定是要求的多数元素
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(nums)[len(nums)/2]3. Majority Vote Algorithm
Last updated