347. Top K Frequent Elements/692. Top K Frequent Words

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]


非常经典的一道题,有以下几点:
1. 按照frequent 排序, 显然要建立 num : freq 的 map对, 定义 map_freq<Integer,Integer> 来存放
2. 要把Map.Entry 放在PQ 里,所以要定义PQ的 compartor 函数。 定义 PriorityQueue<Map.Entry<Integer, Integer>> ((o1,o2)->o2.getValue()-o1.getValue())
注意 Map.Entry()可以调用 getValue() 或者getKey()
3. map 里获取 key, value 或者 entry set的方法: map.keySet(), map.entrySet(). 注意value 可能会重复,因此不能叫valueSet,而是 map.values()

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        
        Map<Integer,Integer> map = new HashMap<>();
        for(int num: nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        
        PriorityQueue<Map.Entry<Integer,Integer>> queue = new PriorityQueue<>((o1,o2) -> o2.getValue()-o1.getValue());
        
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            queue.add(entry);
        }
        
        List<Integer> result = new ArrayList<>();
        while(k > result.size()){
            result.add(queue.poll().getKey());
        }
        return result;
    }
}

692  和347 几乎一样,但这个是都单词按照频率排序,并且 “If two words have the same frequency, then the word with the lower alphabetical order comes first.” 如果两个单词频率一样,应该按照字母表顺序排序。

这就需要在写PriorityQueue compator 函数时注意一点:

 PriorityQueue<Map.Entry<String,Integer>> ((o1,o2)-> o2.getValue() == o1.getValue()? o1.getKey.compareTo(o2.getKey()) : o2.getValue()-o1.getValue() ) ;

注意: 字符串比较函数是 s1.compareTo(s2).

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        
        Map<String, Integer> map_freq = new HashMap<>();
        for(String word: words){
            map_freq.put(word,map_freq.getOrDefault(word,0)+1);
        }
        
        PriorityQueue<Map.Entry<String,Integer>> max_heap = new PriorityQueue<>((o1,o2)-> (o2.getValue() ==o1.getValue()? o1.getKey().compareTo(o2.getKey()) :o2.getValue()-o1.getValue())  );
        
        for(Map.Entry<String,Integer> entry : map_freq.entrySet()){
            max_heap.add(entry);
        }
        
        List<String> result = new ArrayList<>();
        while(k>result.size()){
            result.add(max_heap.poll().getKey());
        }        
        return result;
    }
}

猜你喜欢

转载自www.cnblogs.com/keepAC/p/10269929.html
今日推荐