Question
Given an integer array
numsand an integerk, return thekmost frequent elements. You may return the answer in any order.
Ideas
- Use the starting array and a hashmap to store frequent elements
- Use a linear pass to count frequencies in mapping
- Sort map by value in reverse (this part is just python semantics)
- Slice values array from mapping and return the first k elements
This solution should in theory by asymptotically faster but in practice is slower due to python fuckery.
The actual optimized solution uses a min-heap where you just pop the min heap k times, append to a list and sent it.