LeetCode 题解工作台

多数元素 II

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 示例 1: 输入: nums = [3,2,3] 输出: [3] 示例 2: 输入: nums = [1] 输出: [1] 示例 3: 输入: nums = [1,2] 输出: [1,2] 提示: 1 4 -10 9 …

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

class Solution: def majorityElement(self, nums: List[int]) -> List[int]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个大小为 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

 

示例 1:

输入:nums = [3,2,3]
输出:[3]

示例 2:

输入:nums = [1]
输出:[1]

示例 3:

输入:nums = [1,2]
输出:[1,2]

 

提示:

  • 1 <= nums.length <= 5 * 104
  • -109 <= nums[i] <= 109

 

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        n1 = n2 = 0
        m1, m2 = 0, 1
        for m in nums:
            if m == m1:
                n1 += 1
            elif m == m2:
                n2 += 1
            elif n1 == 0:
                m1, n1 = m, 1
            elif n2 == 0:
                m2, n2 = m, 1
            else:
                n1, n2 = n1 - 1, n2 - 1
        return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3]
speed

复杂度分析

指标
时间complexity ranges from O(n) with hash counting or Boyer-Moore to O(n log n) with sorting. Space complexity is O(n) for hash map or O(1) for the Boyer-Moore variant. Sorting uses O(1) extra if in-place, otherwise O(n).
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidates tracking due to n/3 frequency limit.

  • question_mark

    Check whether multiple majority elements are possible; signal for Boyer-Moore.

  • question_mark

    Sorting may simplify counts but discuss time-space trade-offs.

warning

常见陷阱

外企场景
  • error

    Failing to consider that at most two elements can exceed n/3 and assuming more candidates.

  • error

    Using hash maps without verifying counts may include false positives.

  • error

    Incorrect integer division when computing ⌊ n/3 ⌋ can yield off-by-one errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Majority Element I where n/2 threshold simplifies to single candidate selection.

  • arrow_right_alt

    Find elements appearing more than n/k times for arbitrary k using extended Boyer-Moore.

  • arrow_right_alt

    Count elements exceeding a dynamic frequency threshold instead of fixed n/3.

help

常见问题

外企场景

多数元素 II题解:数组·哈希·扫描 | LeetCode #229 中等