二分搜索-HihoCoder1128

题目链接:https://hihocoder.com/problemset/problem/1128

题目描述:

题目大意就是要我们编程找出K在数组a中的大小排序后的位置。

代码实现:

#include <cstdio>
#include <algorithm>
using namespace std;
int n,k;
const int MAXN = 1e6+10;
int a[MAXN];
int C(int x){
    if(a[x]==k){
        return 1;
    }else if(a[x]>k){
        return 2;
    }else{
        return 3;
    }
}

void solve(){
    int lb=0,ub=n-1;
    while(ub>=lb){
        int mid=(ub+lb)/2;
        if(C(mid)==1){
            printf("%d\n",mid+1);
            return ;
        }else if(C(mid)==2){//如果搜索范围大了,缩小搜索范围
            ub=mid-1;
        }else{//否则,加大搜索范围
            lb=mid+1;
        }
    }
    printf("-1\n");
}

int main(){
    while(~scanf("%d%d",&n,&k)){
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        solve();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LJHAHA/p/9995306.html
今日推荐