69.Sqrt(x)-Leetcode

作者: analanxingde | 来源:发表于2018-01-29 10:07 被阅读1次

    我的AC方法(暴力)

    class Solution {
    public:
        int mySqrt(int x) {
            int i=1;
            while(x/i>=i)
                i++;
            return i-1;
        }
    };
    

    最优解法

    思想:二分法,每次修改上下边界的值

    class Solution {
    public:
        int mySqrt(int x) {
            if(x<=1) return x;
            int l=0;
            int h=x;
            long long m=1;
            while(h-l>=0)
            {   
                m=l+(h-l)/2;
               // cout<<"m="<<m<<endl;
                if(m*m==x) return m;
                if(m*m<x)
                    l=m+1;
                else
                    h=m-1;
               // cout<<"l="<<l<<";h="<<h<<";m="<<m<<endl;
            }
            return h;
        }
    };
    

    相关文章

      网友评论

        本文标题:69.Sqrt(x)-Leetcode

        本文链接:https://www.haomeiwen.com/subject/zttxzxtx.html