代码改变世界

692. 前K个高频单词

2020-05-04 21:26  tonyniu8  阅读(176)  评论(0编辑  收藏  举报

思路1
1.先把这些词放到一个Map<String,Integer> ,遍历这个输入array,把次数统计出来, 复杂度为o(n),
2.按key 建一个数组,然后把数组,按这个词出现的频率排序。nlog(n)。
3.返回前k个元素

class Solution {
	private Map<String, Integer> wordAndCount = new HashMap<>();

	public List<String> topKFrequent(String[] words, int k) {
		for (String word : words) {
			wordAndCount.put(word, wordAndCount.getOrDefault(word, 0) + 1);
		}
		List<String> candidates = new ArrayList<>(wordAndCount.keySet());
		candidates.sort((String w1, String w2) -> (wordAndCount.get(w1).equals(wordAndCount.get(w2)) ? w1.compareTo(w2)
				: wordAndCount.get(w2).compareTo(wordAndCount.get(w1))));
		List<String> topK = new ArrayList<>();
		for (int i = 0; i < k; i++) {
			topK.add(candidates.get(i));
		}
		return topK;
	}
}