Created
July 9, 2020 19:01
-
-
Save voxqhuy/5f034d4e2c6241b1c9206638a5dc74ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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