LeetCode算法面試題彙總之開始之前(2):求衆數

給定一個大小爲 的數組,找到其中的衆數。衆數是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。

你可以假設數組是非空的,並且給定的數組總是存在衆數。

示例 1:

輸入: [3,2,3]
輸出: 3

示例 2:

輸入: [2,2,1,1,1,2,2]
輸出: 2

解題思路:

首先計算數組長度除以二,得到達到衆數的頻率。然後用字典key是數組元素,value是元素的出現次數。最後循環字典,判斷次數是否大於衆數的頻率。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        fre = len(nums) // 2
        result = {}
        number = 0
        for i in nums:
            if i not in result:
                result[i] = 1
            else:
                result[i] += 1
        for j in result:
            if result[j] > fre:
                number = j
                break
        return number
        

 

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