Top K Frequent Elements

Given an integer array and an integer k, return the k most frequent elements. When value counts are the key, bucket-based or frequency-sorted approaches can replace a full sort of all elements.

Input Format

nums = array of integers, k = number of most frequent values

Output Format

k most frequent elements

Constraints

  • 1 <= nums.length <= 10^5; -10^4 <= nums[i] <= 10^4; 1 <= k <= number of distinct elements

Examples

Example 1:

Input:

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

Output:

[1,2]

Explanation:

1 is the most frequent, followed by 2.

Example 2:

Input:

nums = [1]
k = 1

Output:

[1]

Explanation:

Only one element exists.

Loading...
Top K Frequent Elements