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
}
网友评论