Skip to content

Latest commit

 

History

History
19 lines (19 loc) · 456 Bytes

692前k个高频单词.md

File metadata and controls

19 lines (19 loc) · 456 Bytes
func topKFrequent(words []string, k int) []string {
    var res []string
    counts := make(map[string]int)
    for _, word := range words {
        counts[word]++
    }
    for word := range counts {
        res = append(res, word)
    }
    sort.Slice(res, func(i, j int) bool {
        if counts[res[i]] == counts[res[j]] {
            return res[i] < res[j]
        }
        return counts[res[i]] > counts[res[j]]
    })
    return res[:k]
}