給定一個(gè)大小為 n 的數(shù)組,找到其中的眾數(shù)。眾數(shù)是指在數(shù)組中出現(xiàn)次數(shù)大于 ? n/2 ? 的元素。
你可以假設(shè)數(shù)組是非空的,并且給定的數(shù)組總是存在眾數(shù)。
示例 1:
輸入: [3,2,3]
輸出: 3
示例 2:
輸入: [2,2,1,1,1,2,2]
輸出: 2
解法一:
滿足題干要求的眾數(shù)若存在,則僅可能存在一個(gè)
- 用dict來(lái)存儲(chǔ)每個(gè)數(shù)字出現(xiàn)的次數(shù)
- 根據(jù)出現(xiàn)次數(shù)排序
- 判斷出現(xiàn)次數(shù)最多的元素,其出現(xiàn)次數(shù)是否超過(guò)len/2 +1
python代碼:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
cnt = length // 2 + 1
cnt_dict = {}
for i in nums:
if i in cnt_dict:
cnt_dict[i] += 1
else:
cnt_dict[i] = 1
cnt_dict = sorted(cnt_dict.items(), key=lambda x:x[1])
print(cnt_dict)
if cnt_dict[-1][1] >= cnt:
return cnt_dict[-1][0]
else:
return 0
注意
- python中的sorted()函數(shù)可以對(duì)list和dict排序,對(duì)list排序比較簡(jiǎn)單:
x = [1,3,4,2]
y = sorted(x)
輸出為
y = [1,2,3,4]
對(duì)dict排序時(shí)需要制定按照哪個(gè)值來(lái)排序,并且返回的是一個(gè)list,詳見(jiàn):
https://www.runoob.com/python/python-func-sorted.html
值得注意的是,為了方便起見(jiàn),這里直接用了dict.items()將dict轉(zhuǎn)換成了一個(gè)list
dict = { 'one': 1, 'two': 2}
dict.items() = [('one',1), ('two',2)]
解法二:
眾數(shù)出現(xiàn)的次數(shù)一定大于其他所有元素出現(xiàn)次數(shù)之和
- 遍歷數(shù)組,記錄兩個(gè)數(shù)res,cnt
- 若當(dāng)前元素和res相等,則cnt + 1,不相等則 cnt - 1, cnt等于0時(shí),res等于當(dāng)前元素
- 遍歷結(jié)束后res的值可能為眾數(shù),但還需要檢查是否滿足大于 length/2(因?yàn)橛锌赡芟嗟龋瑒t不滿足)
python代碼
class Solution(object):
def majorityElement(self, nums):
cnt = 0
res = nums[0]
for i in range(len(nums)):
if cnt == 0:
res = nums[i]
cnt = 1
elif res == nums[i]:
cnt += 1
elif res != nums[i]:
cnt -=1
# 判斷出現(xiàn)次數(shù)最多元素的次數(shù)是否滿足題干要求
count = 0
for i in range(len(nums)):
if nums[i] == res:
count +=1
if count > len(nums) / 2:
return res
else:
return 0
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

