Given a non-empty list of words, return thekmost frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input:
["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output:
["i", "love"]
Explanation:
"i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input:
["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output:
["the", "is", "sunny", "day"]
Explanation:
"the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O (nlogk) time and O(n) extra space.
Analysis
Approach 1 - Sorting
Time Complexity: O(NlogN) where N is the length of words. We count the frequency of each word in O(N) time, then we sort the given words in O(NlogN) time.
Space Complexity: O(N), the space used to store our candidates.
Approach 1 - Heap
Min Heap - Keep a k-sized min heap while add keys from the frequency counter, poll the heap until it's empty and reverse the list
Max Heap - Add all keys from the word frequency counter to max heap, and poll k times
Time Complexity: O(Nlogk), where N is the length of words. We count the frequency of each word in O(N) time, then we add NN words to the heap, each in O(logk) time. Finally, we pop from the heap up to kk times. As k \leq Nk≤N, this is O(Nlogk) in total.
Space Complexity: O(N), the space used to store our count.
Solution
Heap - PriorityQueue (50ms 49.63%)
classSolution {publicList<String> topKFrequent(String[] words,int k) {Map<String,Integer> count =newHashMap<String,Integer>();List<String> result =newLinkedList<String>();for (String word : words) {count.put(word,count.getOrDefault(word,0) +1); }Queue<String> pq =newPriorityQueue<String>((w1, w2) ->count.get(w1).equals(count.get(w2)) ?w1.compareTo(w2) :count.get(w2) -count.get(w1));for (String word :count.keySet()) {pq.offer(word); }for (int i =0; i < k; i++) {result.add(pq.poll()); }return result; }}
Heap - PriorityQueue with Custom Class (9ms 100% AC)