[Codility] Lession 4.2 PermCheck

Test URL can be found in extension link
Swift solution:

public func solution(inout A : [Int]) -> Int {
    // The array count shall within certain range
    if A.count > 100000 { return 0 }
    // Set up a dictionary to check whether each element only appear once
    var occurs = Dictionary()
    // The sum expectation of any elements non-repeatable is as following:
    let expSum = A.count * (A.count + 1) / 2
    
    var actSum = 0
    
    for a in A {
        // Each element shall within certain range
        if a > 1000000000 { break }
        // Get actual sum of the array
        actSum += a
        // If found any repeated elements, then this array is not valuable.
        if occurs[a] == nil { occurs[a] = a }
        else { return 0 }
    }
    return expSum == actSum ? 1: 0
}

你可能感兴趣的:([Codility] Lession 4.2 PermCheck)