美文网首页Codility 解决方案 [Swift 3.0]
[Codility] Lession 4.2 PermCheck

[Codility] Lession 4.2 PermCheck

作者: sunlitamo | 来源:发表于2016-07-23 17:16 被阅读60次

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<Int,Int>()
    // 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

    本文链接:https://www.haomeiwen.com/subject/ledwjttx.html