用二分搜索(binary search)来确定在整数A1

//运行时间O(logN) 
#include 
#include 
using namespace std;

//binary search
bool exist(const vector<int>& a) 
{
    int low=0,high=a.size()-1;

    while(low<=high)
    {
        int mid=(low+high)/2;
        if(a[mid]1)
            low=mid+1;
        else if(a[mid]>mid+1)
            high=mid-1;
        else
            return true;
    }
    return false;
}

int main()
{
    vector<int> vi={-5,-3,-1,1,2,3,5,7,8,10};
    if(exist(vi))
        cout << "exist";
    else
        cout << "not exist";
    return 0;
}

 

你可能感兴趣的:(用二分搜索(binary search)来确定在整数A1