⚡Flashcard Drill➔
NeetCode #109LC-229MediumArrays & HashingNC 250
← Back to All Problems

#109 · #229 · Majority Element II(多数元素 II)

📌 Problem Statement & Constraints

Given an integer array nums of size n, find all elements that appear more than n / 3 times. Constraints: 1 <= n <= 5 * 10^4, -10^9 <= nums[i] <= 10^9. The solution must run in O(n) time and use O(1) space.

💡 Core Algorithmic Approaches

  1. At most two elements can appear more than n / 3 times, because three such elements would already exceed n.
  2. Extend Boyer-Moore voting to two candidates. Maintain c1, n1 and c2, n2.
  3. For each element x: if x == c1 increment n1; else if x == c2 increment n2; else if n1 == 0 adopt x as c1; else if n2 == 0 adopt x as c2; else decrement both counters.
  4. Unlike the majority case, existence is not guaranteed, so a second pass must count the occurrences of each candidate and filter those exceeding n / 3.

💻 Benchmark Python3 Implementation

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        c1 = c2 = None
        n1 = n2 = 0
        for x in nums:
            if x == c1:
                n1 += 1
            elif x == c2:
                n2 += 1
            elif n1 == 0:
                c1, n1 = x, 1
            elif n2 == 0:
                c2, n2 = x, 1
            else:
                n1 -= 1          # cancel one vote from each candidate
                n2 -= 1
        # mandatory verification: existence is not guaranteed here
        res = []
        for c in (c1, c2):
            if c is not None and nums.count(c) * 3 > len(nums):
                res.append(c)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass for voting plus one pass for verification (nums.count runs twice, each O(n)).
💾 Space Complexity
O(1): four scalar variables. A Counter would be O(n) space and is the naive baseline.

⚠️ Interview Pitfalls & Follow-ups

  • Skipping the verification pass: the algorithm only guarantees that any element exceeding n/3 must be one of the two candidates -- it does not guarantee the candidates qualify.
  • Forgetting the n1 == 0 / n2 == 0 branches: without them, an element can never become a new candidate once both slots are taken.
  • Decrementing only one counter in the cancel branch: both must be decremented; this is what makes the two-candidate version work.
  • Allowing the same value to occupy both candidate slots: initialising them to None and using elif chains prevents this.
  • Assuming exactly two answers: the result can contain zero, one or two elements.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

多数元素 II

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊n / 3⌋ 次的元素。约束:1 ≤ nums.length ≤ 5 × 10^4;-10^9 ≤ nums[i] ≤ 10^9。进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

核心要点

  • 哈希计数 :统计所有元素的出现次数,收集计数超过 n/3 的。时间 O(n)、空间 O(n),直观但不满足进阶要求。
  • 关键数学事实 :出现次数超过 ⌊n/3⌋ 的元素 最多只有 2 个 。因为若有 3 个都超过 n/3,总数就超过 n,矛盾。
  • Boyer-Moore 扩展版 :同时维护两个候选者 (cand1, cnt1) 与 (cand2, cnt2)。遍历时先判断是否匹配已有候选者;若 cnt 为 0 则占位;都不匹配则两个计数同时减 1。
  • 必须二次验证 :与 169 不同,本题 不保证 存在满足条件的元素,因此投票结束后必须重新遍历一遍,统计两个候选者的真实出现次数,只有超过 ⌊n/3⌋ 的才加入答案。

常见陷阱

  • 忘记二次验证 :这是本题与 169 的 核心区别 。本题不保证存在多数元素,投票算法仍会给出候选者,但它可能只是「票数被抵消后剩下的普通元素」,必须验证。
  • 两个候选者初始值用 0 或 -1 :若用 0 作哨兵,而数组中真有 0 这个元素,会产生误判。应使用 None 哨兵,或改用「cnt == 0 时无条件替换」的写法(本解即如此,用 is not None 判断)。
  • 误以为最多 3 个答案 :阈值是 n/3,因此最多 2 个。写成 3 个候选者会导致抵消逻辑错误。
  • 用 nums.count 时未去重 :若两个候选者恰好相同(在特定输入下可能发生),会重复加入答案,因此需要 if c not in res 或改用集合。

参考实现

class Solution:
    def majorityElement(self, nums: list[int]) -> list[int]:
        cand1 = cand2 = None
        cnt1 = cnt2 = 0
        for x in nums:
            if cand1 is not None and x == cand1:
                cnt1 += 1
            elif cand2 is not None and x == cand2:
                cnt2 += 1
            elif cnt1 == 0:
                cand1, cnt1 = x, 1
            elif cnt2 == 0:
                cand2, cnt2 = x, 1
            else:
                cnt1 -= 1          # 三个不同元素互相抵消
                cnt2 -= 1

        # 关键:投票只给出「候选」,必须二次验证
        res = []
        threshold = len(nums) // 3
        for c in (cand1, cand2):
            if c is not None and nums.count(c) > threshold:
                if c not in res:
                    res.append(c)
        return res