Leetcode 229. Majority Element II

Problem

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Algorithm

When an element's frequency is not among the top two, its count is reset to zero. Otherwise, the algorithm continues tracking that element. This process retains two candidate elements whose potential frequencies may exceed ⌊n/3⌋, followed by a final validation step to confirm whether both have reached the threshold.

Code

python3 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        num1, num2 = None, None
        cnt1, cnt2 = 0, 0
        for num in nums:
            if num1 == num:
                cnt1 += 1
            elif num2 == num:
                cnt2 += 1
            elif cnt1 == 0:
                num1 = num
                cnt1 =  1
            elif cnt2 == 0:
                num2 = num
                cnt2 =  1
            else:
                cnt1 -= 1
                cnt2 -= 1

        cnt1, cnt2 = 0, 0
        for num in nums:
            if num1 == num:
                cnt1 += 1
            if num2 == num:
                cnt2 += 1
        
        ans = []
        if cnt1 > len(nums) // 3:
            ans.append(num1)
        if cnt2 > len(nums) // 3:
            ans.append(num2)
        
        return ans
相关推荐
GreenTea7 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
fqq38 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
Thecozzy10 小时前
大厂 AI Coding 面试大招
人工智能·面试·职场和发展
半夏微凉半夏殇10 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
2501_9065651210 小时前
数学之美探究
算法
oier_Asad.Chen10 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环
Dr.kangder11 小时前
嵌入式面试总结(十五)——异常处理
单片机·面试·职场和发展·系统架构·嵌入式
leisoo809712 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
luj_176814 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
郝学胜-神的一滴15 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程