題目描述:
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
你可以假設數組是非空的,並且給定的數組總是存在多數元素。
示例 1:
輸入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
輸出: 2
思路:如果沒有思路,老規矩上哈希表法。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# 哈希表法(這個方法快被我用爛了)
if not nums:return None
hash_={}
for i in nums:
hash_[i]=hash_.get(i,0)+1
for key,val in hash_.items():
if val > len(nums)//2:
return key