Problem Statement
(Source) 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.
Solution
This problem can be solved using Boyer–Moore majority vote algorithm
(wiki).
There could be at most one majority element that appears more than⌊ n/2 ⌋
times in an array. And here we can assume that “the array is non-empty and the majority element always exist in the array“, so there is no need to do a further check of the occurrence of the possible candidate at the end of the major loop. The only candidate would be the only majority element we are trying to find.
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
x, count = None, 0
for i in xrange(len(nums)):
if count == 0:
x = nums[i]
count = 1
elif nums[i] == x:
count += 1
else:
count -= 1
return x
Complexity analysis
- Time complexity:
O(n)
, where
n
is the size of the given array.
- Space complexity: