692.|692. Top K Frequent Words
Title: Top K Frequent Words
Description:
Given a non-empty list of words, return the k most frequent elements.
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.
Example:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
Difficulty:
Medium
Implement Programming Language:
Go
Answer:
【692.|692. Top K Frequent Words】思路还是通过hash表来统计每个单词出现的次数,key是单词,value是次数,然后kv调转,对次数排序之后,再按照要求把字母取出来就可以了。但是我的解法没有考虑顺序,所以顺序有问题,这个题目提到了,所以我的解法没有通过,后续在思考一下吧,暂时记录一下。
代码:
import (
"sort"
)
//测试没过,因为顺序问题
func TopKFrequent(words []string, k int) []string {
collectionMap := map[string]int{}for _, v := range words {
if intV,ok:=collectionMap[v];
ok{
collectionMap[v] = intV +1
}else{
collectionMap[v] = 1
}
}
res := []string{}
counts := make([]int,0)
for _, v := range collectionMap {
counts = append(counts, v)
}
sort.Ints(counts)
searchResult := counts[len(counts)-k:]for k,v := range collectionMap {
if help(searchResult,v){
res = append(res, k)
}
}
return res
}func help (arr []int,compare int) bool{
for e := range arr {
if compare == arr[e]{
return true
}
}
return false;
}
推荐阅读
- parallels|parallels desktop 解决网络初始化失败问题
- LintCode|LintCode 545 [Top k Largest Number II]
- BNC公链|BNC公链 | Eth2.0测试网Topaz已质押超100万枚ETH
- 前端代码|前端代码 返回顶部 backToTop
- 程序员客栈TOP收入的萌系开发者心得|程序员客栈TOP收入的萌系开发者心得 - 雨晴
- Linux监控工具(atop安装使用)
- GitHub|7 款可替代 top 命令的工具
- Springboot整合RabbitMQ(三)——Topic主题交换机
- 意识到自己没有办法成为|意识到自己没有办法成为 top 1% 的程序员,还应该选择程序员的道路么()
- stopPropagation和stopImmediatePropagation的区别