左闭右开写法
int binarySearch(vector<int>& nums, int target)
{
int left = 0;
int right= nums.size();
int mid = 0;
//[left, mid) mid [mid+1, right)
while(left< right)
{
mid = (right - left) / 2 + left;
if(nums[mid] == target) return mid;
if(nums[mid] < target) left = mid + 1;
if(nums[mid] > target) right = mid;
}
return -1; //未找到target
}
int lowerBound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
int mid = 0;
while(left < right)
{
mid = (right - left) / 2 + left;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
int upperBound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
int mid = 0;
while(left < right)
{
mid = (right - left) / 2 + left;
if (nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。