美文网首页LeetCode刷题
[LeetCode]169,229-求众数

[LeetCode]169,229-求众数

作者: 杏仁小核桃 | 来源:发表于2018-10-26 11:01 被阅读33次

169. 求众数
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例:
输入: [3,2,3] -> 输出: 3
输入: [2,2,1,1,1,2,2] -> 输出: 2

解法1

基本思路, 用字典统计每个数的出现频率, 出现次数大于 n/2 的元素.

class Solution:
    def majorityElement(self, nums):
        dic = {}    # 用于记录每个元素的出现次数
        if len(nums) == 1:
            return nums[0]
        for i in range(len(nums)):
            if nums[i] not in dic:
                dic[nums[i]] = 1
            else:
                dic[nums[i]] += 1
                if dic[nums[i]] > len(nums)//2:
                    return nums[i]

解法2

思路: 快速解法, 先给数组排序, 如果有出现超过 n/2 次数的元素, 必然会出现在中间位置.

class Solution:
    def majorityElement(self, nums):
        nums.sort()
        return nums[(len(nums) // 2)]

229. 求众数 II
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
示例:
输入: [1,1,1,3,3,2,2,2] -> 输出: [1,2]

解法1

思路和上一题解法1相同.

class Solution:
    def majorityElement(self, nums):
        dic = {}
        for i in range(len(nums)):
            if nums[i] not in dic:
                dic[nums[i]] = 1
            else:
                dic[nums[i]] += 1
        res = []    
        for num in dic:
            if dic[num] > len(nums)//3:
                res.append(num)
        return res

解法2

利用collections库里的counter

class Solution:
    def majorityElement(self, nums):
        return [i[0] for i in collections.Counter(nums).items() if i[1] > len(nums) / 3]

相关文章

  • [LeetCode]169,229-求众数

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

  • 找出数组中出现次数大于N/K的所有元素

    leetcode 的求众数1 和 求众数2,然后我们可以把它泛化到K

  • 【LeetCode】求众数

    题目描述: 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可...

  • [leetcode]求众数II

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

  • Leetcode169. 求众数

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

  • python-LeetCode-求众数

    题目:给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设...

  • LeetCode 169.求众数

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

  • Leetcode-169:求众数

    题目描述:给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 思路...

  • LeetCode-168.求众数

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

  • LeetCode-169.求众数

    写在前沿:本文代码均使用C语言编写。 Description:给定一个大小为n的数组,找到其中的众数。众数是指在数...

网友评论

    本文标题:[LeetCode]169,229-求众数

    本文链接:https://www.haomeiwen.com/subject/fglktqtx.html