一个有序数组可能在某个位置旋转了。给定一个目标值,查找并返回这个元素在数组中的位置,如果不存在,则返回-1。假设数组中没有重复值。
举一个例子:【0,1,2,3,4,5,6,7】在4这个数字位置上旋转后变为【4,5,6,7,0,1,2】。搜索4返回0。搜索8返回-1
override func viewDidLoad() {
super.viewDidLoad()
let arr0 = [24,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
let arr1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0]
let arr = arr0
for i in arr{
print(search(arr, target: i, low: 0, high: arr.count - 1))
}
}
func search(_ arr : [Int] , target : Int , low : Int , high : Int) -> Int {
guard low <= high else {
return -1
}
var mid = (low + high) / 2
if arr[mid] == target{
return mid
}
if (arr[mid] >= arr[low]){
//左边为顺序
if target >= arr[low] , target < arr[mid]{
mid -= 1
return search(arr, target: target, low: low, high: mid)
}else{
mid += 1
return search(arr, target: target, low: mid, high: high)
}
}else{
//右边为顺序
if target > arr[mid] , target <= arr[high]{
mid += 1
return search(arr, target: target, low: mid, high: high)
}else{
mid -= 1
return search(arr, target: target, low: low, high: mid)
}
}
}
网友评论