简体   繁体   中英

Find closest number in integer array

Given an array of sorted integers, I want to find the closest value to a given number. Array may contain duplicate values and negative numbers. An example: Input:arr[] = {-5, 2, 5, 6, 7, 8, 8, 9}; Target number = 4 Output: 5

Which is the fastest algorithm? binary search? STL find algortithms?

Thanks for your help.

There is an algorithm in the std library that does almost exactly what you are asking for: std::lower_bound

Returns an iterator pointing to the first element in the range [first, last) that is not less than (ie greater or equal to) value, or last if no such element is found.

You can use this to find the first element that is equal or higher than your target. The answer is either that number of the number that precedes it.


Check the following example:

int find_closest(const vector<int>& A, const int a)
{
    if(A.size() <=0)
        throw std::invalid_argument("empty array");

    const auto lb = std::lower_bound(A.begin(), A.end(), a);
    int ans = lb!= A.end() ? *lb : A.back();
    if (lb != A.begin()) {
        auto prec = lb - 1;
        if (abs(ans - a) > abs(*prec - a))
            ans = *prec;
    }

    return ans;
}

The complexity of this approach is logarithmic in the size of the input collection as lower_bound performs a binary search. This is much faster than a naive solution in which you would loop over the whole collection and check every element one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM