二分查找

二分查找

二分查找的前提

  • 目标函数单调性(单调递增或者递减)
  • 存在上下界(bounded)
  • 能够通过索引访问(index accessible)

代码模块

left, right = 0, len(array) - 1
while left <= right:
     mid = (left + right) / 2
    if  array[mid] == target:
        # find the target!!
        break or return result 
    elif array[mid] < target:
        left = mid + 1
    else:
        right = mid - 1 

在递增数组里

[10,14,19,26,27,31,33,35,42,44]

查找:31

10,14,19,26,27,31,33,35,42,44

0 1 2 3 4 5 6 7 8 9

取中间4 往后5~9取7 5~7取6 5~6取5得出最终结果

x的平方根

//二分法
class Solution {
public:
    int mySqrt(int x) {
        long long i=0;
        long long j=x/2+1;
        while(i<=j)
        {
            long long mid=(i+j)/2;
            long long res=mid*mid;
            if(res==x) return mid;
            else if(res<x) i=mid+1;
            else j=mid-1;
        }
        return j;
    }
};


//牛顿迭代法
class Solution {
public:
    int mySqrt(int x) {
        if(x==0) return 0;
        double last=0;
        double res=1;
        while(last!=res)
        {
            last=res;
            res=(res+x/res)/2;
        }
        return int(res);
    }
};

有效的完全平方数

//数字累加求平方比较相等返回真值
class Solution {
public:
    bool isPerfectSquare(int num) {
        int i=1;
        long n=i*i;
        while(n<=num)
        {
            if(num==n)
            return true;
            else
            {
                i++;
                n=pow(i,2);
            }
        }
        return false;
    }
};
//公式法1=1 4=1+3 9=1+3+5
class Solution {
public:
    bool isPerfectSquare(int num) {
        int i=1;
        while(num>0)
        {
            num-=i;
            i+=2;
        }
        return num==0;
    }
};
//二分法
class Solution {
public:
    bool isPerfectSquare(int num) {
        int start=1;
        int end=num;
        int mid=start+(end-start)/2;
        while(start<=end)
        {
            if(pow(mid,2)>num)
            {
                end=mid-1;
            }
            else if(pow(mid,2)<num)
            {
                start=mid+1;
            }
            else return true;
            mid=(end-start)/2+start;
        }
        return false;
    }
};


原文地址:https://www.cnblogs.com/liugangjiayou/p/12490025.html