第一题用Map+PQ即可
- class Solution {
- /**
- * map: <string ,frequent> "love" -> 2 , "coding" -> 1 , "i" -> 2 , "leetcode" -> 1
- * maxHeap:(按频率排序) "i" -> 2 , "love" -> 2 , "coding" -> 1 , "leetcode" -> 1
- */
- public List<String> topKFrequent(String[] words, int k) {
- HashMap<String, Integer > map = new HashMap<>();
- // Frequent hashmap
- for (String s : words) map.put(s, map.getOrDefault(s,0) + 1);
- // if same frequency, then sort alphabetical .
- PriorityQueue<Map.Entry<String,Integer>> maxHeap = new PriorityQueue<>(k, (a,b) ->
- a.getValue()==b.getValue() ? a.getKey().compareTo(b.getKey()) : b.getValue()-a.getValue());
- for (Map.Entry<String,Integer> entry : map.entrySet() ) maxHeap.add(entry);
- List<String> res = new ArrayList<>();
- while (res.size() < k) res.add(maxHeap.poll().getKey()); //add top k
- return res;
- }
- }
复制代码
|