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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
LeetCode:链接
LeetCode变体:LeetCode229:Majority Element II
和剑指Offer_编程题28:数组中出现次数超过一半的数字很像但不一样,因为他的条件是You may assume that the array is non-empty and the majority element always exist in the array。所以不用后续判断!
第一种方法:摩尔投票法。摩尔投票的思想是用一个计数器进行计数,当一个元素的计数为0时,替换该元素。因为这道题让找次数超过一半的数字,这样的候选人只能有一个!
- 维护一个候选数candidate和计数器counter。遍历数组中所有的元素, 设当前的元素为x,若 counter = 0,则 candidate = x, counter = 1; 否则, 根据candidate 与x是否相等来更新counter(相等+1,不等-1)
- 在遍历一次,判断候选数是否为合法的主元素。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return None
candidate, count = 0, 0
for num in nums:
if candidate == num:
count += 1
elif count == 0:
candidate = num
count = 1
else:
count -= 1
return candidate
第二种方法(其实就是摩尔投票):数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现次数的和还要多。因此我们可以考虑在遍历数组的时候保存两个值:一个是数组的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为零,我们需要保存下一个数字,并把次数设为1。由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = nums[0]
count = 1
for i in range(1, len(nums)):
if nums[i] == ans:
count += 1
else:
count -= 1
if count == 0:
ans = nums[i]
count = 1
count = 0
for i in range(len(nums)):
if nums[i] == ans:
count += 1
return ans if count > len(nums)/2.0 else 0