69. x 的平方根

本文最后更新于:2024年4月20日 下午

问题描述

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

1
2
输入: 4
输出: 2

示例 2:

1
2
3
4
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。

解决方案

暴力解法

时间复杂度:O(N)

1
2
3
4
5
6
7
8
9
class Solution:
def mySqrt(self, x):
if x <= 1:
return x
s = 1
while True:
if s * s > x:
return s - 1
s += 1

二分查找

时间复杂度:O(log(N))

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def mySqrt(self, x):
l = 1
r = x
while l <= r:
m = (r + l) // 2
if m * m > x:
r = m - 1
else:
l = m + 1
return r

牛顿法

时间复杂度:O(log(N))

1
2
3
4
5
6
class Solution:
def mySqrt(self, x):
a= x
while a * a > x:
a = (a + x // a) // 2
return a

69. x 的平方根
https://yance.wiki/69问题描述/
作者
Yance Huang
发布于
2018年6月3日
许可协议