Problem Statement
You are given an integer array. Your task is to return the k most frequent elements from the array.
If two numbers have the same frequency, you may return them in any order.
If the array contains fewer than k unique elements, return all unique elements.
Examples
Example 1:
Input array contains repeated values. The most frequent elements should be returned.
Input: [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
All elements are identical, so the single unique element is the answer.
Input: [1,1,1], k = 1
Output: [1]
Example 3:
Two values share the highest frequencies.
Input: [1,2,3,2,3], k = 2
Output: [2,3]
Example 4:
All elements appear once; any two may be returned.
Input: [1,2,3,4], k = 2
Output: [1,2]
这道 DoorDash 的 面试题 属于非常经典的 Top K 高频元素 题型,重点考察候选人对 HashMap(频次统计)+ Heap 或 Bucket(取出前 K 个) 的熟练程度。
核心步骤很简单:
- 统计每个数字出现的次数
用一个 HashMap 把数字 → 出现次数 记录下来。 - 找到出现频率最高的 K 个元素
常见做法有两类:- 小顶堆方式(保持堆大小为 K)
- 桶排序方式(按照出现次数分桶)
面试官想看的不是代码是否完美,而是你是否能:
- 清晰解释思路
- 明确时间复杂度
- 快速想到如何避免 O(n log n) 全排序
这是 DoorDash、Meta、Google 都非常爱考的基础题,能体现候选人的数据结构能力、思考条理,以及编码过程是否稳健。
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Doordash、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Tiktok 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。