zoukankan      html  css  js  c++  java
  • leetcode-mid-math

    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
                
  • 相关阅读:
    单词接龙
    洛谷 P1015 回文数
    洛谷 P1012 拼数
    codevs 2780 ZZWYYQWZHZ
    专项练习之字符串
    模拟题1
    专项训练之线段树
    复习题之求后序遍历
    复习题之二叉树的遍历
    Hdu 3037 Saving Beans(Lucus定理+乘法逆元)
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10981690.html
Copyright © 2011-2022 走看看