229.求众数

https://leetcode-cn.com/problems/majority-element-ii/

一、暴力

一次遍历,用一个map统计每个数(key)的出现次数(val),最后遍历map找次数>n/3的数

class Solution:
    def majorityElement(self, nums):
        map = {}
        n = len(nums)
        res = []
        for num in nums:
            map[num] = map.get(num, 0) + 1
        for key in map:
            if map[key] > n//3:
                res.append(key)
        return res

最后更新于