|
| 1 | +package algorithm.Week_02.id_58; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Comparator; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.PriorityQueue; |
| 9 | + |
| 10 | +/** |
| 11 | + * 692. Top K Frequent Words |
| 12 | + * |
| 13 | + * Given a non-empty list of words, return the k most frequent elements. |
| 14 | + * |
| 15 | + * 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. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 |
| 19 | + * Output: ["i", "love"] |
| 20 | + * Explanation: "i" and "love" are the two most frequent words. |
| 21 | + * Note that "i" comes before "love" due to a lower alphabetical order. |
| 22 | + * Example 2: |
| 23 | + * Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 |
| 24 | + * Output: ["the", "is", "sunny", "day"] |
| 25 | + * Explanation: "the", "is", "sunny" and "day" are the four most frequent words, |
| 26 | + * with the number of occurrence being 4, 3, 2 and 1 respectively. |
| 27 | + * Note: |
| 28 | + * You may assume k is always valid, 1 ≤ k ≤ number of unique elements. |
| 29 | + * Input words contain only lowercase letters. |
| 30 | + * Follow up: |
| 31 | + * Try to solve it in O(n log k) time and O(n) extra space. |
| 32 | + * |
| 33 | + * 分析 : 这里是取最大的值,可以借助Java里的最大堆的数据结构 PriorityQueue |
| 34 | + * @auther: guangjun.ma |
| 35 | + * @date: 2019/4/27 17:07 |
| 36 | + * @version: 1.0 |
| 37 | + */ |
| 38 | +public class LeetCode_692_058 { |
| 39 | + public List<String> topKFrequent(String[] words, int k) { |
| 40 | + Map<String,Integer> map = new HashMap(); |
| 41 | + |
| 42 | + //把元素都放入到map中 |
| 43 | + for(String s : words){ |
| 44 | + map.put(s,map.getOrDefault(s,0) + 1); |
| 45 | + } |
| 46 | + |
| 47 | + //优先队列 最大堆 |
| 48 | + PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<String,Integer>>(){ |
| 49 | + @Override |
| 50 | + public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2){ |
| 51 | + if(o1.getValue() .equals(o2.getValue()) ){ |
| 52 | + return o1.getKey().compareTo(o2.getKey()); |
| 53 | + } |
| 54 | + return o2.getValue() - o1.getValue(); |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + //将map中的元素加入到队列中 |
| 59 | + queue.addAll(map.entrySet()); |
| 60 | + |
| 61 | + //依次取出k个值 |
| 62 | + List<String> res = new ArrayList<>(k); |
| 63 | + for(int i = 0; i <k ; i++){ |
| 64 | + res.add(queue.poll().getKey()); |
| 65 | + } |
| 66 | + return res; |
| 67 | + |
| 68 | + } |
| 69 | +} |
0 commit comments