Problem
- We’re given an input array of
nums
and an integerk
. Our function should return thek
most frequent elements innums
. The result doesn’t need to be sorted can be in any order.
Example
Approach 1
- To solve this we can use a hash map to keep track of the frequency of each number and create a bucket to organize the frequency of our numbers. While we don’t need the buckets to solve the problem, using our hash map to find the most frequent
k
numbers would cost usO(nlogn)
after sorting.
Todo
- Create a frequency map
- Create the buckets
- Count the frequency of each number and store in hash map
- Append to bucket, where index is the frequency and value the num
- Traverse the bucket in reverse and return result, break at k items
Implementation
Complexity Analysis
- Time Complexity:
- Space Complexity: