劍指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