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
相关推荐
手写码匠11 分钟前
深入解析大模型架构之争:全能通用模型 vs 领域专精模型
人工智能·深度学习·算法·aigc
浅念-36 分钟前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
列星随旋1 小时前
线段树和树状数组的学习
学习·算法
圣保罗的大教堂2 小时前
leetcode 61. 旋转链表 中等
leetcode
我爱cope3 小时前
【Agent智能体4 | 智能体AI的应用】
数据库·人工智能·职场和发展
全糖可乐气泡水3 小时前
Codex适配国产信创环境安装部署与技术适配全解析
开发语言·git·python·算法·百度
h_a_o777oah3 小时前
状态机+划分型 DP :深度解析K-划分问题下 DP 状态的转移逻辑(洛谷P2679 P2331 附C++代码)
c++·算法·动态规划·acm·状态机dp·划分型dp·滚动数组优化
05候补工程师3 小时前
从算法理想向工程现实的跨越:SLAM 核心架构、思维误区与 Nav2 实战避坑指南
人工智能·算法·安全·架构·机器人
手写码匠5 小时前
Android 17 适配实战指南:新特性解读、隐私变更与迁移全攻略
人工智能·深度学习·算法·aigc