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
相关推荐
JieE2127 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵13 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1117 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0019 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵21 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent