Using binary search, time complexity: O(log(x))

class Solution {
    public int mySqrt(int x) {
       int l=1, r =x;
        while(l<r-1){
            int mid=l+(r-l)/2;
            int temp = x/mid;
            if(temp==mid)
                return mid;
            else if(temp>mid){
                l=mid;
            }else{
                r=mid;
            }
        }
        if(l*l<x)
            return l;
        else 
            return r;
    }
}

 

posted on 2022-03-31 01:01  阳光明媚的菲越  阅读(24)  评论(0编辑  收藏  举报