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
相关推荐
yszaygr213842 分钟前
Verilog参数化游程编码RLE模块
算法
望易1 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络5 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron20 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者2 天前
J6B vio scenario sample
算法