当前位置: 首页 > article >正文

LeetCode 69. Sqrt(x) 解题思路和python代码

题目
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 x
        
        low, high = 0, x
        result = 0
        while low <= high:
            mid = (low + high) // 2
            if mid * mid == x:
                return mid
            elif mid * mid < x:
                low = mid + 1
                result = mid
            elif mid * mid > x:
                high = mid - 1
        return result

http://www.kler.cn/news/340180.html

相关文章:

  • 常见的图像处理算法:Laplacian边缘检测
  • H、Happy Number(2024牛客国庆集训派对day7)
  • PDF无法导出中文
  • ubuntu上類似window的tortosegit的軟件
  • 如何在Chrome、Edge、360、Firefox等浏览器查看网站SSL证书信息?
  • 基于Android11简单分析audio_policy_configuration.xml
  • 【Linux进程间通信】深入探索:Linux下的命名管道与System V共享内存
  • Mythical Beings:Web3游戏如何平衡创造内容、关注度与实现盈利的不可能三角
  • 【Java 问题】基础——序列化
  • 如何使用 vSphere Client 给虚拟机扩容
  • 浅谈C#之SetSocketOption用法
  • 服务器平均响应时间和数据包大小关系大吗?
  • CIME2025深圳国际热管理材料与设备展览会2025.6.25-27
  • maven打包常用命令
  • React事件机制详解
  • 云栖实录 | MaxCompute 迈向下一代的智能云数仓
  • 10.8作业
  • 解决浏览器不支持访问FTP服务器的问题
  • 嵌入式学习-线性表-Day04-队列
  • GitLab flow工作流及其使用