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
相关推荐
jiang_bluetooth1 天前
奈奎斯特第一准则理解和WIFI OFDM的关联
算法
DuHz1 天前
论文精读:大语言模型 (Large Language Models, LLM) —— 一项调查
论文阅读·人工智能·深度学习·算法·机器学习·计算机视觉·语言模型
檀越剑指大厂1 天前
32 万星的面试学习计划 + 内网穿透工具,程序员面试准备效率翻倍!
学习·面试·职场和发展
中仕公考1 天前
中仕公考:事业编有试用期吗?
职场和发展
加农炮手Jinx1 天前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
精神阿祝1 天前
“八股文”在程序员面试中的价值:助力还是阻力?
面试·职场和发展
借雨醉东风1 天前
程序分享--常见算法/编程面试题:旋转矩阵
c++·线性代数·算法·面试·职场和发展·矩阵
code-is-poetry1 天前
经典领导力书籍推荐,组织决策和管理层必读
职场和发展
逻辑驱动的ken1 天前
Java高频面试考点场景题14
java·开发语言·深度学习·面试·职场和发展·求职招聘·春招
_深海凉_1 天前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展