问题描述
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
例子

image.png
解题思路:
第一种思路:利用字典计数,统计每一个数字的出现次数,提取次数大于n//3的数字。
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
t=len(nums)//3
dic={}
for i in nums:
if i not in dic:
dic[i]=1
else:
dic[i]+=1
res=[]
for i,j in dic.items():
if j>t:
res.append(i)
return res
第二种思路:摩尔投票法。
1 因为寻找的是大于n//3的数字,因此可以判定这样的数字不超过 2个。
2 因此 先设定两个候选值,遍历数组,如果是第一个候选值,则其次数加一,然后如果是第二个候选值,其次数加一,如果都不是,则两个候选值次数都减一,
3 留下来的两个候选值是数组出现次数最多的两个数字
4 最后判断这两个数字出现次数是否大于n//3
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
m, m_count, n, n_count = 0, 0, 1, 0 #两个候选值
for num in nums:
if num == m: #投票
m_count += 1
elif num == n:
n_count += 1
elif m_count == 0:#更换候选值
m = num
m_count = 1
elif n_count == 0:
n = num
n_count = 1
else: #减一
m_count -= 1
n_count -= 1
print("m_count",m_count)
print("n_conut",n_count)
third = len(nums)/3
res = []
if m_count > 0:
if nums.count(m) > third:
res.append(m)
if n_count > 0:
if nums.count(n) > third:
res.append(n)
return res
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island