题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如,输入一个长度为9的数组{1, 2, 3, 2, 2, 2, 5, 4, 2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
思路
数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现的次数还要多。
因此我们在遍历数组的时候保存两个值:一个是数组中的数字result;另一个是次数time。当我们遍历到下一个数字的时候,
如果下一个数字与之前保存的数字相同,则次数+1,否则次数-1;
如果当前次数为0,则保存下一个数字,并把次数设为1。
由于我们要找的数字出现的次数比其他所有数字出现的次数还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。
这个思路叫摩尔投票法。
摩尔投票法:当一个数的重复次数超过数组长度的一半,每次将两个不相同的数删除,最终剩下的就是要找的数。
实例分析
数组nums={1, 2, 3, 2, 2, 2, 5, 4, 2}
初始化,result=nums[0]=1;time=1;
开始遍历数组,index表示数组索引:
index=1,nums[1]=2,与result不相等,则time-1=0,此时result=nums[1]=2,time=1;
index=2,nums[2]=3,与result不相等,则time-1=0,此时result=nums[2]=3,time=1;
index=3,nums[3]=2,与result不相等,则time-1=0,此时result=nums[3]=2,time=1;
index=4,nums[4]=2,与result相等,则time+1=2,result不变;
index=5,nums[5]=2,与result相等,则time+1=3,result不变;
index=6,nums[6]=5,与result不相等,则time-1=2,result不变;
index=7,nums[7]=4,与result不相等,则time-1=1,result不变;
index=8,nums[8]=2,与result相等,则time+1=2,result不变;
结束循环。
测试用例
解法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
result = nums[0]
time = 1
for index in range(len(nums)):
if nums[index]==result:
time+=1
else:
time-=1
if time==0:
result=nums[index]
time=1
return result
复杂度分析
时间复杂度为O(n),空间复杂度O(1)。