LeetCode 题解工作台

最大频率元素计数

给你一个由 正整数 组成的数组 nums 。 返回数组 nums 中所有具有 最大 频率的元素的 总频率 。 元素的 频率 是指该元素在数组中出现的次数。 示例 1: 输入: nums = [1,2,2,3,1,4] 输出: 4 解释: 元素 1 和 2 的频率为 2 ,是数组中的最大频率。 因此具…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以用一个哈希表或数组 记录每个元素出现的次数。 然后我们遍历 ,找到出现次数最多的元素,记其出现次数为 ,累加出现次数等于 的元素的出现次数,即为答案。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 正整数 组成的数组 nums

返回数组 nums 中所有具有 最大 频率的元素的 总频率

元素的 频率 是指该元素在数组中出现的次数。

 

示例 1:

输入:nums = [1,2,2,3,1,4]
输出:4
解释:元素 1 和 2 的频率为 2 ,是数组中的最大频率。
因此具有最大频率的元素在数组中的数量是 4 。

示例 2:

输入:nums = [1,2,3,4,5]
输出:5
解释:数组中的所有元素的频率都为 1 ,是最大频率。
因此具有最大频率的元素在数组中的数量是 5 。

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
lightbulb

解题思路

方法一:计数

我们可以用一个哈希表或数组 cntcnt 记录每个元素出现的次数。

然后我们遍历 cntcnt,找到出现次数最多的元素,记其出现次数为 mxmx,累加出现次数等于 mxmx 的元素的出现次数,即为答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        mx = max(cnt.values())
        return sum(x for x in cnt.values() if x == mx)
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    The interviewer mentions finding frequencies of all elements, which strongly points to a counting map before any final calculation.

  • question_mark

    If they ask why the answer for [1,2,2,3,1,4] is 4 instead of 2, they are testing whether you sum frequencies rather than count distinct winners.

  • question_mark

    If they emphasize Easy plus Array and Hash Table, they usually want a direct counting pass, not sorting or nested scans.

warning

常见陷阱

外企场景
  • error

    Returning the number of elements with maximum frequency instead of the total of their frequencies.

  • error

    Tracking the maximum frequency correctly but forgetting to do a second pass to add all tied frequencies.

  • error

    Using repeated scans for each number, which works on tiny inputs but misses the intended hash lookup pattern.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the actual values whose frequencies are tied for the maximum instead of the summed frequency total.

  • arrow_right_alt

    Update the answer for a stream of numbers where frequencies change after each insertion.

  • arrow_right_alt

    Solve the same task with a fixed-size counting array because nums[i] is bounded by 100.

help

常见问题

外企场景

最大频率元素计数题解:数组·哈希·扫描 | LeetCode #3005 简单