1. 题目
Given a non-negative integer x
, return the square root of x
rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
- For example, do not use
pow(x, 0.5)
in c++ orx ** 0.5
in python.
Example 1:
Input: x = 4 Output: 2 Explanation: The square root of 4 is 2, so we return 2.
Example 2:
Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
2. 思路
这里采用二分查找来逼近平方根的值,设置搜索范围为[0,x] ,然后取之间值的平方和x进行比较, 如果中间值的平方小于x,那么说明所要找的值在左边,将left = mid +1 ,如果大于 说明在右边
让right = mid +1 ,最终left > right 返回最终的result
3. 代码
3.1 二分查找
class Solution {
public:
int mySqrt(int x) {
if(x == 0 || x == 1)
{
return x ;
}
//采用二分查找的办法实现
int left = 0 ;
int right = x ;
int ans = -1; //为了保存得到的ans
while( left <= right )
{
int mid = (left + (right - left) / 2 ) ;
if(mid <= x / mid ) //这里是mid的平方 这样写是为了防止溢出
{
ans = mid ;
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return ans;
}
};
3.2 笨办法
class Solution {
public:
int mySqrt(int x) {
if(x == 0 || x == 1)
{
return x ;
}
int ans = -1 ;
for(long i = 0 ; i*i <= x ; i++)
{
ans = i ;
}
return ans ;
}
};
4. 总结
二分查找是一种高效的搜索算法, 适用于已经排序的数组或者列表,基本思想是不断将搜索区间一分为二,根据目标值和中间值的大小关系,决定继续搜索的方向:
4.1 二分法的基本流程:
1.初始化左右边界: 搜索的左边界left设置为数组的第一个元素的索引, 右边界right设置为数组的最后一个元素
2.进入循环: 使用循环来不断缩小搜索的范围 直到左边界大于右边界为止 (while (left<= right)
3.计算中间值 : 计算左右边界的中间值 mid = (left + right) / 2
4.比较目标值和中间值
如果中间值小于目标值 : 说明目标值在中间值的右侧, 将左边界更新为mid +1
如果中间值大于目标值 : 说明目标值在中间值的左侧, 将右边界更新为mid -1
如果中间值等于目标值: 搜素结束,返回中间值的索引或者其他信息
5.重复步骤3 和 4 直到左边界大于右边界, 循环结束
6.根据实际问题需求,可能需要返回搜索的结果,如找到目标值的索引,或返回某些特定的信息
二分查找的优点: 每次能将搜索减半,因此它的时间复杂度为O(log n) 其中n表示数组或者列表的大小
缺点: 数组或者列表必须是有序的,否则无法找到目标值