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; }

    推荐阅读