Swift using dictionary and Array(dict.keys).sort()


  • 0
    X

    run time may be nlogn for the array sorting function;
    Firstly we put the numbers and their frequency into a dictionary as [num : freq];
    Then sort the keys into an array, loop through the array and keep counting to k, so find the top k's item; feeling it's not the best solution in swift, is there an easy way to do this??

    class Solution {
        func findKthLargest(_ nums: [Int], _ k: Int) -> Int {
    
            if nums.count == 1 {
                return nums[0]
            }
            var numCount = [Int:Int]() // [num : count] dictionary;
            for n in nums {
                if let count = numCount[n] {
                    numCount[n] = count + 1
                }else{
                    numCount[n] = 1
                }
            } // sort numbers, then compair their frequency;
            let sortNum = Array(numCount.keys).sorted { $0 > $1 }
    
            var topK = k
            for num in sortNum { // find the top k's item;
                if let cnt = numCount[num] {
                    topK -= cnt 
                }
                if topK <= 0 {
                    return num
                }
            }
            return 0        
        }
    }
    

Log in to reply
 

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