LeetCode 热题100-97 多数元素

多数元素

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

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

示例 1:

复制代码
输入:nums = [3,2,3]
输出:3

示例 2:

复制代码
输入:nums = [2,2,1,1,1,2,2]
输出:2

提示:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

**进阶:**尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

这个题目最先想到的是hashmap,直接遍历统计就好,然后找出来,但是这样时间复杂是o(n),空间复杂也是o(n);达不到进阶的要求...qwq

python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        hashmap = {}
        for i in nums:hashmap[i] = 1 if i not in hashmap else hashmap[i]+1
        for i,v in hashmap.items():
            if v>=len(nums)//2+1:return i

然后看了看k大佬的解析,发现其实还能用数组排序来做,数组中间的数一定是最后的多数元素

另外进阶的方法应该是 摩尔投票的方法 用一个vote来标志当前考察元素的票数,然后如果一样的话则vote+1,否则-1.这样当vote=-1的时候说明考察元素需要更换了,以此类推下去即可找到最多的那个多数元素

python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        vote = 0
        idx = 0
        res = nums[idx]
        while idx<len(nums):
            vote = vote + 1 if res == nums[idx] else vote - 1
            if vote == -1:
                res = nums[idx]
                vote = 1
            idx+=1
        return res
相关推荐
devilnumber2 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
大貔貅喝啤酒3 小时前
Python Requests库教程
自动化测试·python·requests库
copyer_xyf4 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf4 小时前
Prompt 组织管理
后端·python·agent
‎ദ്ദിᵔ.˛.ᵔ₎4 小时前
双指针、滑动窗口、前缀和、二分查找 算法
算法
shimly1234565 小时前
python3 uvicorn 是啥?
python
顾北顾5 小时前
多头注意力机制
人工智能·深度学习·算法
H178535090965 小时前
SolidWorks_基于草图的实体特征20_特征错误排查
算法·3d建模·solidworks
hujinyuan201605 小时前
2025年12月中国电子学会青少年机器人技术等级考试试卷(二级) 真题+答案
人工智能·算法·机器人
CTA量化套保5 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链