#347 Top K Frequent Elements
Given an integer array nums and an integer k, return the k values
that occur most often in the array. The answer may be returned in any order,
and you can assume it's unique. No ties force a choice between two equally
frequent values for the last slot.
Examples
Input
nums = [1, 1, 1, 2, 2, 3], k = 2Output
[1, 2]1 appears three times and 2 appears twice; 3's single appearance loses.
Input
nums = [1], k = 1Output
[1]One element, one winner.
Constraints
1 ≤ nums.length ≤ 10⁵-10⁴ ≤ nums[i] ≤ 10⁴1 ≤ k ≤ number of distinct elementsThe answer is guaranteed to be unique
The explainer is the good part.
Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.
Want a taste first? Try a free sample: Two Sum or Valid Parentheses.