1. 程式人生 > >【LeetCode】求眾數

【LeetCode】求眾數

spa def style col majority leet target 其中 出現

給定一個大小為 n 的數組,找到其中的眾數。眾數是指在數組中出現次數大於 ? n/2 ? 的元素。

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

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) < 2:
            return nums[0]
        target = len(nums) / 2
        num_dic 
= {} for i in nums: if i in num_dic.keys(): num_dic[i] += 1 else: num_dic[i] = 1 if num_dic[i] > target: return i

【LeetCode】求眾數