LeetCode探索之旅(17)-69求根号

继续刷LeetCode,第69题,求一个非负数的根号。

分析:
求根号的时候,自然是从1开始,平方是否等于所给数,不然就加一,继续求平方,这样其实是相当于从头到尾遍历查找有序表。刚刚开始写的代码就是这样,最后运行时间过长,虽然节省了一半的时间(只需要找到一半的位置即可)。为了缩减查找效率,可以采用类似二分查找的方式,快速找到。

问题:
1、抽象问题的方法,该题目可以抽象为查找问题;
2、二分查找的上下限设置。

附上第一次代码:

class Solution {
public:
    int mySqrt(int x) {
        int m=x/2;
        if(x==0)
            return 0;
        long i=1;
        for(;i<=m;i++)
        {
            if(i*i<=x&&(i+1)*(i+1)>x)
                break;
        }
        return i;
    }
};

第二个代码(采用类似二分查找):

class Solution {
public:
    int mySqrt(int x) {
        int m=x/2;
        if(x<2)
            return x;
        long low=0;
        long mid,high=x;
        while(low<high)
        {
            mid=(high+low)/2;
            if(x/mid==mid)
                return mid;
            else if(x/mid>mid)
                low=mid+1;
            else
                high=mid;
        }
        return high-1;
    }
};

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/87935865