您的位置:首页 > 其它

LeetCode #169: Majority Element

2016-09-22 11:07 423 查看

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: O(1), only a variable for counter and a variable for possible candidate are in need.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  主投票