692. Top K Frequent Words


https://leetcode.com/problems/top-k-frequent-words/


Runtime: 12 ms, faster than 8.91% of Go online submissions for Top K Frequent Words.
Memory Usage: 4.5 MB, less than 40.59% of Go online submissions for Top K Frequent Words.


```go
package main

import (
	"fmt"
	"sort"
)

type Pair struct {
	Key   string
	Value int
}

type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { 
    if (p[i].Value == p[j].Value) {
        return p[i].Key < p[j].Key
    } else {
        return p[i].Value > p[j].Value
    }
}

func sortMapByKeyAndValue(m map[string]int) PairList {
	p := make(PairList, len(m))
	i := 0
	for k, v := range m {
		p[i] = Pair{k, v}
        i += 1
	}
	sort.Sort(p)
	return p
}

func topKFrequent(words []string, k int) []string {
	//12:00
	count_dict := make(map[string]int, 0)
	for _, word := range words {
		_, ok := count_dict[word]
		if ok {
			count_dict[word] += 1
		} else {
			count_dict[word] = 1
		}
	}
	results := make([]string, 0)
	sorted := sortMapByKeyAndValue(count_dict)[:k]
	for _, value := range sorted {
		results = append(results, value.Key)
	}
	return results
	//12:10
    //debug
}
```
