hihocoder 二分

题目

一个简单的二分,只是想说明一下,如若要查找一个数组中某个数的下标可以直接用lower_bound()这个函数。只是要考虑到要查找的数不在数组中的这种情况。

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int Max = 1e6+5;
long long  a[Max];
int n;
long long m;
void solve()
{
    int L=0,R=n-1,mid;
    while(R>=L)
    {
        mid = (R+L)/2;
        if(a[mid]==m)
        {
            printf("%d\n",mid+1);
            return;
        }else if(a[mid]>m){
            R=mid-1;
        }else{
            L=mid+1;
        }
    }
    printf("-1\n");
}

int main()
{
    scanf("%d%lld",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%lld",&a[i]);
    sort(a,a+n);
 //   solve();
   int loc = lower_bound(a,a+n,m)-a;
    if(a[loc]==m)//查找到底数不是我要的数
        printf("%d\n",loc+1);
    else
        printf("-1\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qie_wei/article/details/81117715