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
相关推荐
2401_8898846610 小时前
高性能计算通信库
开发语言·c++·算法
不想看见40411 小时前
Hamming Distance位运算基础问题--力扣101算法题解笔记
算法
像污秽一样11 小时前
算法与设计与分析-习题4.1
算法·链表·排序算法
lhc2009062511 小时前
【作业】 贪心算法
算法·贪心算法
天若有情67311 小时前
循环条件隐藏陷阱:我发现了「同循环双条件竞态问题」
c++·学习·算法·编程范式·while循环··竞态
j_xxx404_11 小时前
C++算法:前缀和与哈希表实战
数据结构·算法·leetcode
We་ct12 小时前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
mit6.82412 小时前
tabbi风波|开源协议
算法
是梦终空11612 小时前
C++中的职责链模式变体
开发语言·c++·算法
仰泳的熊猫12 小时前
题目2270:蓝桥杯2016年第七届真题-四平方和
c++·算法·蓝桥杯