100. Top K Frequent Elements

Medium · Heap

Given an array of integers and an integer k, return the k most frequent elements. You may return the answer in any order.

You are guaranteed that the answer is unique (the k-th most frequent element is strictly more frequent than the (k+1)-th most frequent element, if it exists).

Examples

Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: The element 1 appears 3 times, element 2 appears 2 times, and element 3 appears 1 time. The 2 most frequent elements are 1 and 2.
Example 2
Input: nums = [4,1,1,1,2,2,3], k = 1
Output: [1]
Explanation: The element 1 appears 3 times, which is the most frequent. Return [1].

Constraints