Find the nearest/closest value in a sorted List

前端 未结 8 1619
我寻月下人不归
我寻月下人不归 2020-12-05 10:59

I was wondering if it is possible to find the closest element in a List for a element that is not there.

For example if we had the valu

8条回答
  •  情深已故
    2020-12-05 11:30

    There are two methods to achieve the result-

    1. lower_bound
    2. binary search

    I prefer to use the lower_bound method, it's short :)

    int pos=lower_bound(v.begin(),v.end(),value);
    if(pos!=0&&target!=v[pos])
        if(abs(v[pos]-value)>abs(value-v[pos-1]))
            pos=pos-1;
    

    For binary search, you can refer to the above answers, as my code will seem like a copy paste of their code. Note that I have declared the array globally here.

    binarysearch(int low,int high,int val)
    {
        if(val<=arr[0])
            return 0;
        if(val>=arr[n-1])
            return arr[n-1];
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(v[mid]>val)
                return binarysearch(low,mid-1,val);
            else if(v[mid]=abs(val-v[high]))
            return high;
        else 
            return low;
    }
    

提交回复
热议问题