C++ number range (binary search)

Given an integer array of length n arranged in ascending order, and q queries.
For each query, return the starting position and ending position of an element k (the position starts counting from 0).
If the element does not exist in the array, "-1 -1" is returned.
Input format The
first line contains integers n and q, indicating the length of the array and the number of queries.
The second line contains n integers (all in the range of 1 to 10000), representing a complete array.
Next q lines, each line contains an integer k, which represents a query element.
Output format
A total of q lines, each line contains two integers, indicating the starting position and ending position of the element to be sought.
If the element does not exist in the array, "-1 -1" is returned.
Data range
1≤n≤100000
1≤q≤10000
1≤k≤10000
Input example:
6 3
1 2 2 3 3 4
3
4
5
Output example:
3 4
5 5
-1 -1

AC code:

#include<stdio.h>
#include<algorithm>

int a[100010];
int n,q;
int head,tail;

void binary(int x)
{
    
    
    int l=-1,r=n;
    int middle;
    head=n-1;
    tail=0;

    while(l+1!=r)//找第一个大于等于x的位置
    {
    
    
        //求最小,向下取整
        middle=l+((r-l)>>1);
        if(a[middle]<x){
    
    
            l=middle;
        }
        else if(a[middle]>=x){
    
    
            r=middle;
            if(a[middle]==x) head=std::min(head,middle);
        }
    }
    if(a[head]==x){
    
    //x存在则继续找第一个小于等于x的位置

        l=middle-1;
        r=n;
        while(l+1!=r)
        {
    
    
            //求最大,向上取整
            middle=l+((r-l+1)>>1);
            if(a[middle]<=x){
    
    
                l=middle;
                if(a[middle]==x) tail=std::max(tail,middle);
            }
            else if(a[middle]>x){
    
    
                r=middle;
            }
        }
    }
    else {
    
    //x不存在
        head=-1;
        tail=-1;
    }
}

int main()
{
    
    
    scanf("%d%d",&n,&q);
    for(int i=0;i<n;++i)
    {
    
    
        scanf("%d",&a[i]);
    }
    for(int i=0;i<q;++i)
    {
    
    
        int x;
        scanf("%d",&x);
        binary(x);
        printf("%d %d\n",head,tail);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108771110