題目
https://www.lintcode.com/problem/majority-element/description?_from=ladder&&fromId=2
實現
- 設置一個 count ,作爲“浮標”,遍歷數組。再設置一個 current_major 來記錄當前出現次數最多的數
- 如果
current_major == nums[i]
那麼count ++
,否則count --
,這裏的 count 就像是浮標一樣,如果發現 count 爲 0 了,說明當前元素出現次數會 大於等於 之前次數出現較多的元素
代碼
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majorityNumber(self, nums):
current_major = 0
count = 0
for i in range(len(nums)):
if count == 0:
current_major = nums[i]
if nums[i] == current_major:
count += 1
else:
count -= 1
return current_major