GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/java/692_Top_K_Frequent_Words.java at master · anandanthony/leetcode Expand file tree/ Copy path692_Top_K_Frequent_Words.javaMore file actions 32 lines (29 loc) · 1.19 KB / Copy path692_Top_K_Frequent_Words.javaFile metadata and controls32 lines (29 loc) · 1.19 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 class Solution { /*public List<String> topKFrequent(String[] words, int k) { Map<String, Integer> count = new HashMap(); for (String word: words) { count.put(word, count.getOrDefault(word, 0) + 1); } List<String> candidates = new ArrayList(count.keySet()); Collections.sort(candidates, (w1, w2) -> count.get(w1).equals(count.get(w2)) ? w1.compareTo(w2) : count.get(w2) - count.get(w1)); return candidates.subList(0, k); }*/ public List<String> topKFrequent(String[] words, int k) { Map<String, Integer> count = new HashMap(); for (String word: words) { count.put(word, count.getOrDefault(word, 0) + 1); } PriorityQueue<String> heap = new PriorityQueue<String>( (w1, w2) -> count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2) ); for (String word: count.keySet()) { heap.offer(word); if (heap.size() > k) heap.poll(); } List<String> ans = new ArrayList(); while (!heap.isEmpty()) ans.add(heap.poll()); Collections.reverse(ans); return ans; } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |