All problems

Top K Frequent Elements

Medium · heap

Given a list of integers nums and an integer k, return the k values that appear most often in nums.

You can return them in any order. Only the values matter, not how many times each one appears. The answer is guaranteed to be unique: the kth most frequent value always appears strictly more often than the next one, so there is no tie at the cutoff.

Examples

Example 1

Input: nums = [1, 1, 1, 2, 2, 3], k = 2

Output: [1, 2]

1 appears 3 times, 2 appears twice and 3 only once, so the top two are 1 and 2.

Example 2

Input: nums = [5], k = 1

Output: [5]

Example 3

Input: nums = [4, 4, 6, 6, 6, 5, 5, 5, 5], k = 2

Output: [5, 6]

5 appears 4 times and 6 appears 3 times. 4 appears only twice, so it misses the cut.

Constraints