1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第六十九题
(1)题目
英文:
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.
中文:
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
(2)解法
① 用现有的方法
(耗时:44ms,内存:13.6M)
class Solution:
def mySqrt(self, x: int) -> int:
return int(x **0.5)
或者
(耗时:44ms,内存:13.6M)
class Solution:
def mySqrt(self, x: int) -> int:
import math
return int(math.sqrt(x))
注意:
1.这两种方法其实是一个方法,输出的原始数据都是float的,所以必须使用int。
② 二分查找(耗时:44ms,内存:13.6M)
class Solution:
def mySqrt(self, x: int) -> int:
if x==1 or x==0:
return x
left = 1
right = x // 2
while left<=right:
mid = (left+right) // 2
if x >= mid*mid and x < (mid+1)*(mid+1):
return mid
elif x < mid*mid:
right = mid - 1
elif x >= (mid+1)*(mid+1):
left = mid +1
return mid
注意:
1.最开始right设为x//2的原因是,如果直接从1,2,…,j,…x中找j^2<x中最接近的j会很麻烦,所以直接将x除2,理由是:从x=1开始,越往后面,(x//2)的平方要远大于x,而选取x//2作为right比x要简单很多。