HashMap Solution Using Swift 4


  • 0
    U
    class Solution {
        func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
            var hashMap = [Int:Int]()
            
            
            // O(|nums|) <= O(n)
            for num in nums {
                if let oldValue = hashMap[num] {
                    hashMap[num] = oldValue + 1
                } else {
                    hashMap[num] = 1
                }
            }
            
            
            // O(n log n)
            var i = 0
            var topKFrequentArray:[Int] = []
            for (key, value) in hashMap.sorted(by: {$0.value > $1.value}) {
                if i < k {
                    topKFrequentArray.append(key)
                    i+=1
                }
            }
        
            return topKFrequentArray
        }
    }
    
    let solution = Solution()
    solution.topKFrequent([1,1,1,1,2,2,3,3,4,5,6,8,8,8,8,8,8,8,8,8,8], 3)
    

    Should output [8,1,2]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.