Lonely Integer

  • + 0 comments

    here is my solution using dictionary with Swift

    func lonelyinteger(a: [Int]) -> Int {
        // Write your code here
        var dict: [Int: Int] = [:]
        // create Dictionary based on array that we have
        for number in a {
            // check that number is in Dictionary
            if dict.contains(where: {$0.key == number}) {
                // add counter when already in it
                dict[number]! += 1
            } else {
                // initiate new number
                dict[number] = 1
            }
        }
        // get first dictionary where it has only one value
        if let aloneNumber = dict.first(where: {$0.value == 1}) {
            return aloneNumber.key
        }
        return 0
    }