본문 바로가기

Computer Science/Algorithm with Code

Hacker Rank_5/54 tests (Easy, Lonely Integer)

Given an array of integers, where all elements but one occur twice, find the unique element.

Example

a = [1, 2, 4, 3, 3, 2, 1]

The unique element is 4.

func lonelyinteger(a: [Int]) -> Int {

    var dics = [Int : Int]()
    for i in a {
        if dics[i] == nil {
            dics[i] = 1
        } else {
            dics[i]! += 1
        }
    }
    
    return dics.first{ $0.value == 1 }!.key
}