mycode   memory error

class Solution(object):
    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

        for i in range(2,x//2):
            if i**2 > x :
                return i-1

 

参考:

1、但是下面这个可以过!!!难道range会存储???????????

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0 :return 0
        k = 1
        res = 1
        while (k+1)*(k+1) <= x:    
            k += 1
        return k

2、

class Solution(object):
    def mySqrt(self, x):
        return int(x**0.5)

3、  我也试了类似二分的方法想缩小范围,但是没有成功。。。

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        if x == 1 or x==0:
            return x
        
        begin , last = 0, x
        #当x>1时, 0*0<x,x*x>x
        while begin < last:
            mid = (begin + last)//2
            
            if mid**2 == x:
                return mid
            elif mid**2 > x :
                last = mid 
            
            elif mid**2 < x:
                if (mid+1)**2 > x:
                    return mid
                else:
                    begin = mid 
        
        return -1