LeetCode - Top K Frequent Words

Given a non-empty list of words, return the k most 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(n log k) time and O(n) extra space.

  先用 hashmap 存储string 和出现次数的映射, 然后insert并维持一个size为K的priorityqueue (注意要自己定义compare 函数),最后会得到top Kth words 但是是从小到大排序,注意要reverse:

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        if(words == null || words.length == 0 || k <= 0){
            return new ArrayList<String>();
        }
        Map<String, Integer> map = new HashMap<>();
        PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((e1, e2) -> compareElement(e1,e2));
        for(String str : words){
            map.put(str, map.getOrDefault(str, 0)+1);
        }
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            pq.add(entry);
            if(pq.size() > k){
                pq.poll();
            }
        }
        List<String> res = new ArrayList<>();
        while(!pq.isEmpty()){
            res.add(pq.poll().getKey());
        }
        Collections.reverse(res);
        return res;
    }
    
    private int compareElement(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2){
        if(e1.getValue() - e2.getValue() != 0) 
            {return e1.getValue() - e2.getValue();} 
        else
            {return e2.getKey().compareTo(e1.getKey());}
    }
}

  

猜你喜欢

转载自www.cnblogs.com/incrediblechangshuo/p/9694614.html
今日推荐