Top K Frequent Elements
Medium
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- k is in the range [1, the number of unique elements in the array].
- It is guaranteed that the answer is unique.
Example
Input: nums = [1,1,1,2,2,3], k = 2
Expected Output: [1, 2]
Edge Cases
- If `k` equals the number of unique elements, return all elements.
- If all elements have the same frequency, any `k` elements can be returned.
- If the array contains negative numbers, nothing changes since frequency depends only on occurrence, not value.