代码随想录:二分查找
二分法标志:数组顺序排列且无重复
简单的二分法,写法是左闭右闭的写法,此种情况的left可以等于right,故while里有等号。
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int middle;
while (left <= right) {
middle = (left + right) / 2;
if (target > nums[middle])
{
left = middle + 1;
} else if (target < nums[middle]) {
right = middle - 1;
} else if (target == nums[middle]) {
return middle;
}
}
return -1;
}
};
标签:二分,right,nums,int,随想录,middle,查找,left
From: https://www.cnblogs.com/huigugu/p/18544924