Top K Frequent Words

来源:互联网 发布:福昕阅读器破解版mac 编辑:程序博客网 时间:2024/06/05 19:50

Given a list of words and an integer k, return the top k frequent words in the list.

 Notice

You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.

Example

Given

[    "yes", "lint", "code",    "yes", "code", "baby",    "you", "baby", "chrome",    "safari", "lint", "code",    "body", "lint", "code"]

for k = 3, return ["code", "lint", "baby"].

for k = 4, return ["code", "lint", "baby", "yes"],

使用heap sort的方式去做,其中的一个重点是自定义比较器

定义比较器的时候,首相是按照出现的次数进行定义,当出现的此时相同时,然后在按照字典顺序进行排序,在使用String中的compareTo方法时,需要注意的一点是,String的compareTo方法的返回值与compare中要求的返回值的类型一直但是数值相反,因此要反向使用。

java

class Type {    String word;    int count;    public Type(String word, int count) {        this.word = word;        this.count = count;    }}public class Solution {    /*     * @param words: an array of string     * @param k: An integer     * @return: an array of string     */    public String[] topKFrequentWords(String[] words, int k) {        // write your code here        if (words == null || words.length == 0) {            return words;        }        if (k == 0) {            return new String[]{};        }        Comparator<Type> cmp = new Comparator<Type>() {            public int compare(Type a, Type b) {                if (a.count != b.count) {                    return a.count - b.count;                } else {                    return b.word.compareTo(a.word);                }            }        };        Queue<Type> heap = new PriorityQueue<>(k, cmp);        Map<String, Integer> map = new HashMap<>();        for (int i = 0; i < words.length; i++) {            if (map.containsKey(words[i])) {                map.put(words[i], map.get(words[i]) + 1);            } else {                map.put(words[i], 1);            }        }        for (String str : map.keySet()) {            Type type = new Type(str, map.get(str));            heap.offer(type);            if (heap.size() > k) {                heap.poll();            }        }        String[] res = new String[k--];        while (!heap.isEmpty()) {            res[k--] = heap.poll().word;        }        return res;    }}


原创粉丝点击