leetcode python3 简单题169. Majority Element

本文介绍在VSCode环境中解决LeetCode上的“多数元素”问题。通过三种不同方法实现,包括利用collections.Counter、先过滤再计数以及使用hash表。每种方法都附有详细的代码实现及性能数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第一百六十九题

(1)题目
英文:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

(2)解法
① 使用现成的collections.Counter
(耗时:44ms,内存:15.2M)

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        return [k for k, v in collections.Counter(nums).items() if v>len(nums)//2][0]

② 先用set过滤掉重复的元素,然后再用count来计数
(耗时:40ms,内存:15.1M)

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        set1 = set(nums)
        for i in set1:
            if nums.count(i) > (len(nums)//2):
                return i

③ 使用hash表,也就是生成一个key为元素,value为出现次数的dict
(耗时:56ms,内存:15.2M)

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        dic = {}
        set1 = set(nums)
        for i in nums:
            dic[i] = dic.get(i,0) + 1
        for i in set1:
            if dic.get(i)>(len(nums)//2):
                return i

注意:
1.get函数是获取i的value,也就是出现的次数,如果没有找到i,则是第一次出现,返回0次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值