文章目录
- 题目描述
- 法一 二分查找
题目描述
法一 二分查找
int bsearch_1(int l, int r)
{while (l < r){int mid = (l + r)/2;if (check(mid)) r = mid;else l = mid + 1;}return l;
}
int bsearch_2(int l, int r)
{while (l < r){int mid = ( l + r + 1 ) /2;if (check(mid)) l = mid;else r = mid - 1;}return l;
}
vector<int> searchRange(vector<int>& nums, int target){if(nums.empty()) return {-1, -1};int l=0, r=nums.size()-1;while(l<r){int mid = (l+r)/2;if(nums[mid]>=target) r=mid;else l=mid+1;}if(nums[r]!=target) return {-1, -1};int L=r;l=0, r=nums.size() - 1;while(l<r){int mid = (l + r + 1)/2;if(nums[mid] <= target) l=mid;else r=mid-1;}return {L, r};}