704. 二分查找
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-search/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while(left <= right){
int middle = left + (right - left) / 2;
if(target > nums[middle]){
left = middle + 1;
}else if(target < nums[middle]){
right = middle - 1;
}else{
return middle;
}
}
return -1;
}
};