这题还真的挺难的,明天好好看看二分
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x, res = -1;
while(l <= r){
int mid = l + (r-l)/2;
if((long long)mid*mid <= x){
res = mid;
l = mid + 1;
}
else{
r = mid-1;
}
}
return res;
}
};
class Solution {
public:
int mySqrt(int x) {
if(x <= 1) return x;
int l = 1, r = x;
int res = 0;
//不是具体找某个数
//既然不知道到底要返回什么值,我们肯定要把每个数都检查一遍
while(l <= r){
int mid = l + (r-l)/2;
//当mid*mid<=x时对res赋值,因为x的开方取整后平方一定小于x,所以一定是在这个时候取到答案
if(x / mid >= mid){
res = mid;
l = mid+1;
}
else{
r = mid-1;
}
}
return res;
}
};
很难
class Solution {
public:
int mySqrt(int x) {
//二分或者线性都可以
if(x == 0) return 0;
int left = 1, right = x;
int mid;
int res = 0;
//因为不知道要具体返回哪个值,所以要把每个数都遍历完
while(left <= right){
int mid = left + (right-left)/2;
if(x/mid >= mid){
//记录一下res,因为小于等于就有可能是答案
//因为mid已经被记录过了,所以直接跳过
res = mid;
left = mid+1;
}
else{
right = mid-1;
}
}
return res;
}
};