【LeetCode 简单题】38-求众数

声明:

今天是第38道题。给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

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

示例 1:

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

示例 2:

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

解法1。常规解法就是把nums数组里的每个元素存到字典中,键值为出现频数,然后遍历这个字典,返回键值>n/2的键。提交中击败了78.78% 的用户,代码如下。

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

解法2。利用set()数据结构自动去重的特点,以及python自带的.count()函数对每个元素进行频数统计返回大于n/2的元素。在提交中击败了93.56% 的用户,代码如下。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        unique = set(nums)
        for i in unique:
            if nums.count(i)>len(nums)/2:
                return i
        return None

解法3。题干假定数组中一定存在众数(出现频数>n/2),所以可对数组进行排序返回中间的值,肯定是众数,在提交中击败了78.78% 的用户,代码如下。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sorted(nums)[len(nums)/2] 

解法4。利用max来求得最大值,可以先创建1个字典存放元素和其出现频数,再利用max可迭代的特性,求取字典中键值最大对应的元素,在提交中击败了78.78% 的用户,代码如下。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict = {}
        for i in nums:
            if i not in nums:
                dict[i] = 1
            else:
                dict[i] += 1
        # dict.items()返回可遍历的(键, 值) 元组数组,比较key = dict.items()的键值,也就是第2个元素的最大值
        # 最后取这个元组的第1个元素即键
        return max(dict.items(), key=lambda x: x[1])[0]

 

结尾

解法1:原创

解法2:https://blog.csdn.net/ma412410029/article/details/80528318

解法3:https://blog.csdn.net/qq_34364995/article/details/80544139

解法4:https://blog.csdn.net/qq_34364995/article/details/80544139

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值