有点像是夹出答案!
java的方法,方法的结果好像不那么愉快啊。
class Solution {
public int mySqrt(int x) {
if(x<=1) return x;
for(int i=1;i<=x;i++){
if(i>x/i){
return (int)i-1;
}
}
return -1;
}
}
其实C++的语言也是可以这么写得。但是倒数第二个return就不用去强转了
代码如下:
class Solution {
public:
//硬把结果夹出来
int mySqrt(int x) {
if(x<=1) return x;
//144
//1 4 9 16 25 36 49 64 91 100 121 144
for(long long s=1;s<=x;++s){
//s*s>x:表明找到解
if(s*s>x) return s-1;
}
return -1;
}
};
但是跑出来的结果倒是蛮不错的
但是速度还是不够快。
看看花花酱大神的解析后,发现这是查找的体。因为就是给你一个数,肯定是在比这个数小的数的区间中寻找结果。比如25,肯定是在[1,24]之间找一个数是他的结果。所以这个体有查找的感觉。
相比于上面的写法:二分法可以明显减少上面迭代的次数。
class Solution {
public:
int mySqrt(int x) {
long l=1;
long r=x;
while(l<=r){
//m是二分点
int m=l+(r-l)/2;
if(m>x/m){
r=m-1;
}
else{
l=m+1;
}
}
return r;
}
};