leetcode二分法模板1:二分法
int mySqrt(int x){
left = 0;
right = x;
while(left<right){
mid = left+(right-left)/2;
if(long mid*mid>x){
right = mid-1;
}else if(long mid*mid<x){
left = mid+1;
}else{
return true;//找到了
}
return false;//没找到,如果要寻找位置
// 当前后指针穿过的时候返回位置就是left或者right+1
}
模板可解决的题目如下:
69 :求解X的平方根 https://leetcode.cn/problems/sqrtx/
367:有效的平放式 https://leetcode.cn/problems/valid-perfect-square/description/
704:二分查找 https://leetcode.cn/problems/binary-search/description/
35:搜索插入位置 https://leetcode.cn/problems/search-insert-position/description/