记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
2、数据结构:
数组
3、题解:
方法1:哈希表统计法
设置一个字典,将numbers中的数字和出现的次数对应起来,判断出现大于一半的长度即可。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
count = {}
lens = len(numbers)
for num in numbers:
if num in count:
count[num] += 1
else:
count[num] = 1
if count[num] > (lens >> 1):
return num
return 0
方法2:数组排序法
排序,众数超过一半,中点的数一定是所求的值。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
#排序法
if not numbers:
return None
numbers.sort()
#判断是否超过1/2
mid = len(numbers) // 2
x = numbers[mid]
count = 0
for num in numbers:
if num == x:
count += 1
if count > mid :
return x
return 0
方法3:摩尔投票法
正负抵消
伪代码:
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
#摩尔投票法
#找到可能的数
votes = 0
for num in numbers:
if votes == 0:
x = num
votes += 1 if num == x else -1
#统计出现的次数
count = 0
for num in numbers:
if num == x:
count += 1
return x if count > (len(numbers) >> 1) else 0
4、复杂度分析:
方法1:
时间复杂度:O(N)
空间复杂度:O(N)
方法2:
时间复杂度:O(NlogN)
空间复杂度:O(1)
方法3:
时间复杂度:O(N)
空间复杂度:O(1)