69. Sqrt(x)(分治)

来源:互联网 发布:linux restart命令 编辑:程序博客网 时间:2024/06/05 09:39

题目:

Implement int sqrt(int x).

Compute and return the square root of x.

求平方根,用二分法,时间复杂度为O(lgN)

代码:

public class Solution {    public int mySqrt(int x) {        if(x<2)return x;        int left =1,right=x/2,last_mid=0;        while(left<=right)        {        int mid= left+(right-left)/2;        if(x/mid<mid)        {        right=mid-1;//        last_mid=mid;        }        else if(x/mid>mid)        {        left=mid+1;        //如果未能找到相等的,去小于该值的平方根        last_mid=mid;         }        else        {        return mid;        }        }        return last_mid;    }}


0 0
原创粉丝点击