Skip to content

Instantly share code, notes, and snippets.

@piyush23dez
Created August 4, 2019 07:04
Show Gist options
  • Save piyush23dez/2244cb1a69ad6792e5ea448780208165 to your computer and use it in GitHub Desktop.
Save piyush23dez/2244cb1a69ad6792e5ea448780208165 to your computer and use it in GitHub Desktop.
func topkFrequentWords(_ words: [String], _ k: Int) -> [String] {
var hashMap = [String:Int]()
for word in words {
hashMap[word] = (hashMap[word] ?? 0) + 1
}
var keys = Array(hashMap.keys)
keys.sort {
let f1 = hashMap[$0] ?? 0 // get ob associated w/ key 1
let f2 = hashMap[$1] ?? 0 // get ob associated w/ key 2
if f1 == f2 {
return $0 < $1
} else {
return f1 > f2
}
}
print(keys)
return keys
}
let vals = topkFrequentWords(["i", "love", "leetcode", "i", "love", "coding"], 2)
print(vals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment