题目描述
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
解释
给一堆数字,如果一个数字出现的次数占数字总数的一半以上,我们叫他majority element。现在要把这个majority找出来。保证majority element存在且数组非空。
思路
思路1 排序+sliding window
我们首先把数组排序,这样保证了所有相同的元素会连续出现。此时我们用一个长度为 数组长度一半 + 1 的窗口从0开始滑。只要窗口左边界和右边界的元素一样,则证明该元素就是我们要找的majority element。
时间复杂度 O(nlogn),空间复杂度O(1)
思路2 哈希
我们用字典把每个元素出现过的次数统计出来,然后对字典遍历,如果字典的某一个value比数组长度的一半要大,则该value对应的key即为我们要找的majority element。
时间复杂度O(n),空间复杂度O(n)
思路3 摩尔投票法
用一个counter来计数,设一个暂时结果为res,然后对数组进行遍历。如果当前数字和res相同则counter加1,不同则counter减1。如果counter等于0,则把暂时见过替换为数组当前遍历到的值。在遍历结束时,暂时结果即为最终结果。
时间复杂度O(n),空间复杂度O(1)。
代码
思路1代码
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
n = len(nums)
for i in range(n // 2 + 1):
if nums[i] == nums[n // 2 + i]:
return nums[i]
思路2代码
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import collections
c = collections.Counter(nums)
for key in c:
if c[key] > len(nums) // 2:
return key
思路3代码
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 1
res = nums[0]
for i in range(1, len(nums)):
if count == 0:
res = nums[i]
count = 1
else:
if nums[i] == res:
count += 1
else:
count -= 1
return res