leetcode - 704. 二分查找
题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/363c63abdd63807243037a0c9062c523.png)
代码
#include <iostream>
#include <vector>
using namespace std;
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right){
int mid = left + (right - left) /2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] > target){
right = mid - 1;
}
}
return -1;
}
int main(){
int res;
int n;
cin>>n;
vector<int> nums(n);
int target;
for(int i = 0; i < n; i++){
cin>>nums[i];
}
cin>>target;
res = search(nums, target);
cout<<res;
return 0;
}