給定一個大小爲 n 的數組,找到其中的衆數。衆數是指在數組中出現次數大於 ⌊ n/2 ⌋
的元素。
你可以假設數組是非空的,並且給定的數組總是存在衆數。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
newset=set(nums)
for i in newset:
if nums.count(i)>len(nums)/2:
return i
思路如下:這個題是我比較得意的,已經超過百分之八十用Python做題的人.哈哈,人生苦短,我用Python
1.利用集合去重,得到沒有重複元素的集合
2.遍歷集合,對應數組中數組求個數並比較火的就結論