150强访谈简单

前 K 个频繁元素

“前 K 个频繁元素”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个整数数组 nums 和一个整数 k,返回 k 最频繁的元素。您可以按任何顺序返回答案。

编写一个函数 topKFrequent(nums: List[int], k: int) -> List[int]

约束条件
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in nums]
  • The answer is guaranteed to be unique

示例

Example 1
Input
nums = [1, 1, 1, 2, 2, 3], k = 2
Output
[1, 2]
Explanation

1 appears 3 times and 2 appears 2 times. These are the 2 most frequent elements.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

There is only one element, so it is the most frequent.

Need a Hint?
考虑使用数组和哈希特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。