美文网首页Codility 解决方案 [Swift 3.0]
[Codility] Lession 4.1 FrogRiver

[Codility] Lession 4.1 FrogRiver

作者: sunlitamo | 来源:发表于2016-07-23 12:45 被阅读122次

    Test URL can be found in extension link
    Swift solution:

    public func solution(X : Int, inout _ A : [Int]) -> Int {
     
        // Make sure this array is not empty
        guard A.count > 0 else { return 0 }
        // Make sure the value of X is valid,otherwise return -1
        guard X >= 0 else { return -1 }
        // If X == 0 means the expected position is 0 ,which the frog currently located.
        if X == 0 { return 0 }
        
        var result = -1
        var validCount = X
        //Define a boolean array to record which position has been covered by the leafs.
        var arr = [Bool](count:X,repeatedValue: false)
        
        for i in 0 ..< A.count {
    
            if arr[A[i] - 1] == false {
                arr[A[i] - 1] = true
                validCount -= 1
            }
            
            if validCount == 0 {
                result = i
                break
            }
        }
        return result
    }
    

    相关文章

      网友评论

        本文标题:[Codility] Lession 4.1 FrogRiver

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