简体   繁体   English

在 integer 数组中查找最接近的数字

[英]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};一个例子: Input:arr[] = {-5, 2, 5, 6, 7, 8, 8, 9}; Target number = 4 Output: 5目标数 = 4 Output:5

Which is the fastest algorithm?最快的算法是什么? binary search?二进制搜索? STL find algortithms? STL 找到算法?

Thanks for your help.谢谢你的帮助。

There is an algorithm in the std library that does almost exactly what you are asking for: std::lower_bound std库中有一个算法几乎完全符合您的要求: 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.返回一个迭代器,该迭代器指向范围 [first, last) 中不小于(即大于或等于)值的第一个元素,如果没有找到这样的元素,则返回 last。

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.这种方法的复杂性与输入集合的大小成对数,因为lower_bound执行二进制搜索。 This is much faster than a naive solution in which you would loop over the whole collection and check every element one by one.这比一个简单的解决方案要快得多,在这种解决方案中,您将遍历整个集合并逐个检查每个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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