问题描述:
Implement int sqrt(int x).
Compute and return the square root of x.
问题求解:
二分法。O(logN)
class Solution {
public:
int mySqrt(int x) {
long long low =1;
long long high=x;
long long tmp;//用于和x比较
while(low < high)
{//二分法查找1~x里边的数,平方为tmp,与x比较
long long mid = low + (high-low)/2;
tmp = mid*mid;
if(tmp==x) return mid;
else if(tmp > x) high=mid-1;
else low=mid+1;
}
tmp = high*high;
if(tmp > x) return high-1;
else return high;
}
};
本文介绍了一种使用二分法高效计算整数平方根的方法。通过不断缩小搜索范围,可以在O(logN)的时间复杂度内找到最接近的平方根。代码实现简洁且易于理解。
1042

被折叠的 条评论
为什么被折叠?



