#347 Top K Frequent Elements
Contents
Link
https://leetcode.com/problems/top-k-frequent-elements/description/
Solution
- The first step is to build a hash map
element -> its frequency
. This step takesO(N)
time whereN
is a number of elements in the list. - The second step is to build a heap of size
k
usingN
elements*.- To add the first
k
elements takes a linear timeO(k)
in the average case, andO(log1+log2+...+logk)=O(logk!)=O(klogk)
in the worst case. - After the first
k
elements we start to push and pop at each step,N - k
steps in total. The time complexity of heap push/pop isO(logk)
and we do itN - k
times that meansO((N−k)logk)
time complexity. Adding both parts up, we getO(Nlogk)
time complexity for the second step.
- To add the first
- The third and the last step is to convert the heap into an output array. That could be done in
O(klogk)
time.
Code
|
|
Notes
- While writing the custom comparator function, explicitly specifying data type of comp to
bool
gives a function signature error in the initialization ofpriority_queue
.