二分的流程
1.确定二分的边界
2.编写二分的代码框架
3.设计一个check(性质)
4.判断一下区间如何更新
5.如果更新方式写的是l=mid,r=mid-1 ,那么算mid的是时候+1;
6 绿色:(check)R=M,L=M+1 MID=(L+R)/2
红色:(check)L=M,R=M-1MID=(L+R+1)/2
int mySqrt(int x) {
int l=0,r=x;
while(l<r)
{
int mid=l+(long long)r+1 >> 1;
if(mid <= x/mid) l=mid;
else r=mid-1;
}
return r;
}
int searchInsert(vector<int>& nums, int target) {
if(nums.empty() || nums.back() <target) return nums.size();
int l=0,r=nums.size()-1;
while(l<r)
{
int mid=l+r>>1;
if(nums[mid] >= target) r=mid;
else l=mid+1;
}
return r;
}
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=r+l >> 1;
if(nums[mid] >= target) r=mid;
else l=mid+1;
}
if(nums[r]!=target) return {-1,-1};
int start=r;
l=0,r=nums.size()-1;
while(l<r)
{
int mid=r+l+1 >>1;
if(nums[mid] <= target) l=mid;
else r=mid-1;
}
int end=r;
return {start,end};
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty()) return false;
int n=matrix.size(),m=matrix[0].size();
int l=0,r=n*m-1;
while(l<r)
{
int mid=l+r>>1;
if(matrix[mid/m][mid%m]>=target) r=mid;
else l=mid+1;
}
if(matrix[r/m][r%m]==target) return true;
return false;
}
int findMin(vector<int>& nums) {
int l=0,r=nums.size();
while(l<r)
{
int mid=l+r>>1;
if(nums[mid]<=nums.back()) r=mid;
else l=mid+1;
}
return nums[r];
}
int search(vector<int>& nums, int target) {
if(nums.empty()) return -1;
int l=0,r=nums.size()-1;
while(l<r)
{
int mid=l+r>>1;
if(nums[mid]<=nums.back()) r=mid;
else l=mid+1;
}
if(target<=nums.back()) r=nums.size()-1;
else l=0,r--;
while(l<r)
{
int mid=l+r >>1;
if(nums[mid]>=target) r=mid;
else l=mid+1;
}
if(nums[l]==target) return l;
else return -1;
}
int firstBadVersion(int n) {
int l=1,r=n;
while(l<r)
{
int mid=(long long) r+l >>1;
if(isBadVersion(mid)) r=mid;
else l=mid+1;
}
return r;
}
int findPeakElement(vector<int>& nums) {
int l=0,r=nums.size()-1;
while(l<r)
{
int mid=(long long) r+l>>1;
if(nums[mid]>nums[mid+1]) r=mid;
else l=mid+1;
}
return r;
}
int findDuplicate(vector<int>& nums) {
int l=1,r=nums.size()-1;
while(l<r)
{
int mid= l+r >>1;
int cnt=0;
for(auto i:nums)
{
if(i>=l && i<=mid)
cnt++;
}
if(cnt >mid-l+1) r=mid;
else l=mid+1;
}
return r;
}
int hIndex(vector<int>& citations) {
int l=0,r=citations.size();
while(l<r)
{
int mid=l+r+1 >>1;
if(citations[citations.size()-mid]>=mid) l=mid;
else r=mid -1;
}
return r;
}