Skip to content

Instantly share code, notes, and snippets.

@voxqhuy
Created July 9, 2020 19:01
Show Gist options
  • Save voxqhuy/5f034d4e2c6241b1c9206638a5dc74ae to your computer and use it in GitHub Desktop.
Save voxqhuy/5f034d4e2c6241b1c9206638a5dc74ae to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/top-k-frequent-elements/
// O(n), O(n)
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var freqDict = [Int : Int]()
var bucket = [Int : [Int]]()
var result = [Int]()
var topFreq = 0
// O(n)
for num in nums {
let newFreq = freqDict[num, default: 0] + 1
freqDict[num] = newFreq
topFreq = max(topFreq, newFreq)
}
// O(n)
for (num, freq) in freqDict {
bucket[freq, default: []].append(num)
}
// O(topFreq)
while result.count < k {
if let nums = bucket[topFreq] {
result.append(contentsOf: nums)
}
topFreq -= 1
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment