最高频的K个单词

http://www.lintcode.com/zh-cn/problem/top-k-frequent-words/

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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
        Map map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            int count = 1;
            if (map.containsKey(word)) {
                count += map.get(word);
            }
            map.put(word, count);
        }
        String[] res = new String[k];
        Set> entries = map.entrySet();
        List> list = new ArrayList<>(entries);
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                if (o1.getValue() == o2.getValue()) {
                    return o1.getKey().compareTo(o2.getKey());
                }
                return o2.getValue() - o1.getValue();
            }
        });
        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i).getKey();
        }
        return res;

    }
}

你可能感兴趣的:(最高频的K个单词)