iT邦幫忙

0

自主學習30日-LeetCode 169:Majority Element

  • 分享至 

  • xImage
  •  

169.Majority Element

題目

給定一個整數陣列 nums。

找出 出現次數超過 ⌊n/2⌋ 的元素(稱為 Majority Element)。

假設一定存在這樣的元素。

解題思路

假設 majority element 出現次數 > n/2

用 候選元素 + 計數器 遍歷陣列

如果計數器為 0 → 設當前元素為候選元素

如果元素 = 候選 → 計數器 +1

否則計數器 -1

最後候選元素即為 majority element

https://ithelp.ithome.com.tw/upload/images/20251003/20169298igAgAw5hMD.pnghttps://ithelp.ithome.com.tw/upload/images/20251003/20169298HaqT9v3JV7.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言