leetcode 169 python 求众数

2019-02-01  本文已影响0人  慧鑫coming

传送门

题目要求

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:
输入: [3,2,3]
输出: 3

示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2

思路一

遍历数组,以元素为key, 出现次数为value组成字典,当某个key的value大于 n/2 时,它即为众数;或许你可以偷懒使用collections.Counter

→_→ talk is cheap, show me the code

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = dict()
        for i in nums:
            count = d.get(i, 0)
            count += 1
            d[i] = count
            if count > len(nums)/2:
                return i
上一篇下一篇

猜你喜欢

热点阅读