Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
【题目分析】
题目要求实现求平方根(舍小数取整)函数
如果直接从1开始遍历到x寻找,会超时。
问题的症结便集中在怎样最大限度缩小遍历次数
【思路分析】
使用二分查找的思想,缩小查找范围[l,r]
【参考代码_60ms】
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
if x<4:
return 1
l,r=0,x
while l<r:
mid=(l+r)//2
if x>=(mid*mid) and x<(mid+1)*(mid+1):
return mid
if x>(mid*mid):
l=mid
else:
r=mid
return mid
(ps,最暴力方法:446 / 1017 test cases passed.
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
if x==1:
return 1
for i in range(1,x):
if i*i<=x and (i+1)*(i+1)>x:
return i
和寻找规律法:131 / 1017 test cases passed.
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
if x==1 or x==2 or x==3:
return 1
count=1
for i in range(2,x):
if i%2==0:
continue
count+=1
left=(1+i)*count/2
right=(1+i+2)*(count+1)/2
if x>=left and x<right:
return count
均为
Time Limit Exceeded
)