题目:
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.
解法1:
二分法
假设答案为ans,本题本质上是求第一个小于等于x的ans的平方
如x=4,ans为2
x=8,ans也是2
c++中lower_bound函数是求第一个大于等于x的数
c++中upper_bound函数是求第一个大于x的数
解析来源:算法笔记
这时候我们如何求第一个小于等于x的数呢,直接用大于的算法,最后结果直接减1即是结果
参考LeetCode Binary Search Summary 二分搜索法小结
c++:
class Solution {
public:
int mySqrt(int x) {
if(x <= 1) return x;
int left = 0;
int right = x;
while(left < right){
int mid = left + (right - left) / 2;
int square = mid * mid;
if(square > x){
right = mid;
} else {
left = mid + 1;
}
}
return left - 1;
}
}