精華區beta Marginalman 關於我們 聯絡資訊
692. Top K Frequent Words 給予一個字串陣列words和一個數字k,返回出現頻率最高的k種字串列表,若多個字串 出現次數相同,則字母順序較大的優先。 Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation:k為2而 "i" 和 "love" 是出現次數最多的字串。 思路: 1.用一個 HashMap 紀錄所有單字的出現次數。 2.把Map所有的鍵值放入Heap,並按照題目給的規則排序。 3.從Heap中拿出k個元素加入列表後返回。 JavaCode: class Solution { public List<String> topKFrequent(String[] words, int k) { List<String> res = new ArrayList<>(); Map<String, Integer> map = new HashMap<>(); for(String word : words) { map.put(word, map.getOrDefault(word, 0) + 1); } PriorityQueue<String> queue = new PriorityQueue<>( (a, b) -> map.get(a) == map.get(b) ? a.compareTo(b) : map.get(b) - map.get(a) ); for(String key : map.keySet()) queue.offer(key); for(int i = 0; i < k; i++) res.add(queue.poll()); return res; } } 芒果假面 https://i.imgur.com/MKk0ZMM.jpg -- https://i.imgur.com/PIoxddO.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.19.35 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1666143951.A.1FE.html
doramon888: 笑容~ 10/19 16:04