Top K Frequent Elements
Medium
Array
Hash Table
Heap (Priority Queue)
Sorting
Bucket Sort
Given an integer array `nums` and an integer `k`, return *the* `k` *most frequent elements*. You may return the answer in **any order**.
Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2
Input: nums = [1], k = 1
Output: [1]

Constraints

  • 1 <= nums.length <= 10⁵
  • -10⁴ <= nums[i] <= 10⁴
  • k is in the range [1, the number of distinct elements in the array].
  • It is guaranteed that the answer is unique.
Time Complexity
O(n)
Space Complexity
O(n)
14
Case 1
Input: [1,1,1,2,2,3] 2
Expected: [1,2]
Case 2
Input: [1] 1
Expected: [1]
Case 3
Input: [4,1,-1,2,-1,2,3] 2
Expected: [-1,2]