16ms with Swift!


  • 0
    M

    class Solution {
    func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {

        var dictOfNums : [Int: Int] = [:]
        var result : [Int] = []
    
        for i in nums {
            
            if let index = dictOfNums[i] {
                
                dictOfNums.updateValue(dictOfNums[i]! + 1, forKey: i)
                
            } else {
                dictOfNums[i] = 1
            }
    
        }
        
        let sortedArray = dictOfNums.sorted{ $0.value > $1.value }
        
        var count = 0
        for (key, value) in sortedArray {
            
            if(count >= k) {
                break
            }
            
            result.append(key)
            count += 1
        }
        
        return result
        
    }
    

    }


Log in to reply
 

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