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
相关推荐
We་ct1 小时前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
Frostnova丶1 小时前
LeetCode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串
算法·leetcode·哈希算法
历程里程碑2 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
Felven2 小时前
B. 250 Thousand Tons of TNT
算法
victory04313 小时前
PPO GAE优势函数演化和推导
算法
Jasmine_llq3 小时前
《P3572 [POI 2014] PTA-Little Bird》
算法·滑动窗口·单调队列·动态规划(dp)·多组查询处理·循环优化(宏定义 rep)
tankeven3 小时前
HJ101 排序
c++·算法
流云鹤3 小时前
动态规划02
算法·动态规划
小白菜又菜3 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode