当前位置: 首页> 教育> 高考 > 推广方式图片_网页制作员是做什么的_seo 优化 工具_竞价sem托管

推广方式图片_网页制作员是做什么的_seo 优化 工具_竞价sem托管

时间:2025/7/8 19:51:34来源:https://blog.csdn.net/weixin_57266891/article/details/142725261 浏览次数:0次
推广方式图片_网页制作员是做什么的_seo 优化 工具_竞价sem托管

题目
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++ or x ** 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.

Constraints:

0 <= x <= 231 - 1

思路
输入的是一个非负数x,需要返还x的开平方,并且需要是一个向下约的整数。

我们可以使用binary search去完成这个题目。
从[0, x]这个范围开始做binary search,首先检查中间点mid。
如果mid的2次方是x,那么mid就正好是x的开平方。
如果mid的2次方要小于x,证明应该向右移动mid,去找更大的数,将low更新为mid+1。
如果mid的2次方要大于x,证明应该向左移动mid,去找更小的数,将high更新为mid-1。

这个解决方案的time complexity是O(log x)。

class Solution(object):def mySqrt(self, x):""":type x: int:rtype: int"""if x == 0 or x == 1:return xlow, high = 0, xresult = 0while low <= high:mid = (low + high) // 2if mid * mid == x:return midelif mid * mid < x:low = mid + 1result = midelif mid * mid > x:high = mid - 1return result
关键字:推广方式图片_网页制作员是做什么的_seo 优化 工具_竞价sem托管

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: