问题描述
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.
给定一个大小为n的数组,找到多数元素。大多数元素的元素⌊n / 2⌋多次出现。
你可以假设数组是非空的,并且大多数元素始终存在于数组中。
输入: [3,2,3]
输出: 3
输入: [2,2,1,1,1,2,2]
输出: 2
Python 实现
第一种方法:对数组进行排序,然后取中间位置的那个元素,即为主要元素。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
major = nums[len(nums)/2]
return major
第二种方法:博伊尔-摩尔投票算法(Boyer-Moore majority vote algorithm),是一种使用线性时间复杂度和常数空间复杂度来找到数组的主要元素。因此,我们可以采取一种投票的形式,当一个标记的元素重复出现的时候,我们给它投一票,加一分,出现别的元素则对应减一分。当分数为0时,则用下一个元素来作为新的标记元素。这样到最后,出现次数最多的那个元素必然是最后仍然被标记的元素。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = None
score = 0
for num in nums:
if score == 0:
ret = num
# Scoring for the number existing.
if ret == num:
score += 1
else:
score -= 1
return ret