LeetCode 69. Sqrt(x)

简介: 给你一个非负整数 x ,计算并返回 x 的 算术平方根 。

网络异常,图片无法展示
|

题目地址(69. Sqrt(x))

leetcode-cn.com/problems/sq…

题目描述

给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
示例 1:
输入:x = 4
输出:2
示例 2:
输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
提示:
0 <= x <= 231 - 1

思路

就是遍历[0,x]中符合要求的数,用二分法减少时间复杂度

代码

  • 语言支持:Python3

Python3 Code:

class Solution:
    def mySqrt(self, x: int) -> int:
        left,right = 0, x
        res = 0
        while left <= right:
            mid = (left + right)//2
            # print(mid,left,right)
            sqrtX = mid ** 2
            if sqrtX > x:
                right = mid -1
            else:
                res = mid
                left = mid + 1
        return res

复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(logn)O(logn)
  • 空间复杂度:O(1)O(1)
目录
相关文章
|
Java 测试技术 C++
LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单
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.
108 0
LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单
LeetCode 69. Sqrt(x)
实现int sqrt(int x). 计算并返回x的平方根,其中x保证为非负整数. 由于返回类型是整数,因此将截断十进制数字,并仅返回结果的整数部分.
68 0
LeetCode 69. Sqrt(x)
☆打卡算法☆LeetCode 69、Sqrt(x) 算法解析
“给定一个非负整数,计算并返回x的算术平方根。”
[LeetCode]--69. Sqrt(x)
Implement int sqrt(int x). Compute and return the square root of x. 我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。 public int mySqrt(int x) { long start = 1, end = x; while
843 0
LeetCode 69 Sqrt(x)
题目描述: Implement int sqrt(int x). Compute and return the square root of x. 题目翻译:输入x,返回sqrt(x); C语言版: int mySqrt(int x) { int t...
867 0
|
15天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
15天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
16天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值