- Difficulty: Medium
Implement int sqrt(int x).
Compute and return the square root of x.
Subscribe to see which companies asked this question
二分查找,时间复杂度O(logn)
class Solution {
public:
int mySqrt(int x) {
int left = 1, right = x / 2;
int last_mid;
if (x < 2) return x;
while (left <= right) {
const int mid = left + (right - left) / 2;
if (x / mid > mid) {
left = mid + 1;
last_mid = mid;
}
else if (x / mid < mid) {
right = mid - 1;
}
else {
return mid;
}
}
return last_mid;
}
};

本文介绍了一种使用二分查找算法来计算整数平方根的方法。通过不断缩小搜索范围,该算法能在O(logn)的时间复杂度内找到最接近平方根的整数值。
832

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



