非递归版本:
int search(vector<int> &nums,int target)
{
int l = 0;
int r = nums.size() - 1;
while(l <= r)
{
int mid = l + r >> 1;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1
}
递归版本:
int search(vector<int> &nums,int target,int l , int r)
{
if(l < r) return -1;
int mid = r+l >> 1;
if(nums[mid] == target) return mid;
if(nums[mid] > target) return search(nums,target,l,mid-1);
if(nums[mid] < target) return search(nums,target,mid+1,r);
return -1;
}