46. Majority Element

題目

https://www.lintcode.com/problem/majority-element/description?_from=ladder&&fromId=2

實現

  1. 設置一個 count ,作爲“浮標”,遍歷數組。再設置一個 current_major 來記錄當前出現次數最多的數
  2. 如果 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章