Question
Implement int sqrt(int x)
.
Compute and return the square root of x.
本题难度Medium。
二分查找法
【复杂度】
时间 O(logN) 空间 O(1)
【思路】
使用二分法解这题时,通过比较mid^2
和x
大小来确定我们在哪一半中搜索。
【注意】
helper
中除了x,其他的变量都是long型,目的就是防止overflow。
【代码】
public class Solution {
public int mySqrt(int x) {
//require
if(x<=0)
return 0;
//invariant
long ans=helper((long)0,(long)x,x);
//ensure
return (int)ans;
}
private long helper(long min,long max,int x){
//base case
if(min+1==max){
return (max*max<=x)?max:min;
}
long mid=(min+max)/2;
long res=mid*mid;
if(res==x)
return mid;
else if(x<res)
return helper(min,mid,x);
else
return helper(mid,max,x);
}
}