剑指offer26 — 数组中出现次数超过一半的数字
题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
分析 & 解
-
dict
方法:# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here numsCount = {} numLen = len(numbers) for num in numbers: if num in numsCount: numsCount[num] += 1 else: numsCount[num] = 1 if numsCount[num] > (numLen>>1): return num return 0
时间复杂度和空间复杂度都是O(n)
-
如果有大于一半的数字,那么两两不等则抵消掉,最后剩下的即有可能是那个大于一半的数字。空间复杂度为O(1):
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here last = 0 lastCount = 0 for num in numbers: if lastCount == 0: last = num lastCount = 1 else: if num == last: lastCount += 1 else: lastCount -= 1 if lastCount == 0: return 0 else: lastCount = 0 for num in numbers: if num == last: lastCount += 1 if lastCount > (len(numbers)>>1): return last return 0