LeetCode 题解工作台
最大频率元素计数
给你一个由 正整数 组成的数组 nums 。 返回数组 nums 中所有具有 最大 频率的元素的 总频率 。 元素的 频率 是指该元素在数组中出现的次数。 示例 1: 输入: nums = [1,2,2,3,1,4] 输出: 4 解释: 元素 1 和 2 的频率为 2 ,是数组中的最大频率。 因此具…
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表或数组 记录每个元素出现的次数。 然后我们遍历 ,找到出现次数最多的元素,记其出现次数为 ,累加出现次数等于 的元素的出现次数,即为答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个由 正整数 组成的数组 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 <= 1001 <= nums[i] <= 100
解题思路
方法一:计数
我们可以用一个哈希表或数组 记录每个元素出现的次数。
然后我们遍历 ,找到出现次数最多的元素,记其出现次数为 ,累加出现次数等于 的元素的出现次数,即为答案。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.