题干:
二分搜索有序数组模板题。寻找一个数。
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
解:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size()-1;
int ans = -1;
while(left <= right){
int mid = left + ((right - left) >> 1);
if(nums[mid] == target){
ans = mid;
break;
}
else if(nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
}
return ans;
}