题目:在数组A[0..n-1]中,有所谓的魔术索引,满足条件A[i]=i。给定一个升序数组,元素值各不相同,编写一个方法,判断在数组A中是否存在魔术索引.
数组中不存在重复数据可以通过二分法来实现:
func magicFast(arr:inout [Int],start:Int,end:Int) -> Int {
if arr.count == 0 || start < 0 || end >= arr.count || end < start {
return -1
}
let mid:Int = (start + end) / 2
let midValue:Int = arr[mid]
if mid == midValue {
return mid
} else if midValue > mid {
return magicFast(arr: &arr, start: start, end: mid - 1)
} else {
return magicFast(arr: &arr, start: mid + 1, end: end)
}
}
数据中存在重复数据:
func magicFast2(arr:inout [Int],start:Int,end:Int) -> Int {
if arr.count == 0 || start < 0 || end >= arr.count || end < start {
return -1
}
let mid:Int = (start + end) / 2
let midValue:Int = arr[mid]
if mid == midValue {
return mid
}
let leftIndex:Int = min(mid - 1, midValue)
let left:Int = magicFast2(arr: &arr, start: start, end: leftIndex)
if left >= 0 {
return left
}
let rightIndex:Int = max(mid + 1, midValue)
let right:Int = magicFast2(arr: &arr, start: rightIndex, end: end)
return right
}
测试代码:
var magicArr:[Int] = [-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13]
var magicIndex:Int = recursion.magicFast(arr: &magicArr, start: 0, end: magicArr.count - 1)
print("FlyElephant---\(magicArr)中间值:\(magicIndex)")
magicArr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]
magicIndex = recursion.magicFast2(arr: &magicArr, start: 0, end: magicArr.count - 1)
print("FlyElephant---\(magicArr)中间值:\(magicIndex)")