c# - 数字列表 - 如何高效查找小于或等于 N 的最大数字

标签 c# algorithm

假设我有一组固定的数字,并且恰好已排序:

static readonly int[] numbers = new int {
    1, 200, 204, 228, 298, 300, 331, 332, ... 2983
};

如何有效地找到小于或等于任意值的最大数字。我试图创建的函数如下:

public int LessThanOrEqualTo(int n)
{
    // ???
}

最简单的方法是每次迭代该集合。不过,我正在寻找一种方法来加快速度。我可以将其转换为其他格式,例如 IDictionary ,但想不出一个聪明的方法来立即做到这一点。

最佳答案

回答了一个非常相似的问题here

Use Array.BinarySearch. If the input is in the list, it will return the index, and if not then it will return the complement of the index of the first larger value. You just invert the result and subtract one to get the index of the closest smaller value.

关于c# - 数字列表 - 如何高效查找小于或等于 N 的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051054/

相关文章:

c# - 仅将特定 VM 用于 TFS 构建

c# - 为 SEO 友好的博客正确设置自定义路由

algorithm - 找到长度为 k 的子序列,其总和等于给定的总和

javascript - 对我自己排序的数组进行排序的有效方法

c# - 相互比较两个 k-d 树(2D 点)的快速算法?

c# - 一行 LINQ 将 string[] 展平为字符串?

c# - swagger ui中的OData查询

algorithm - 如何使用算术运算用给定的数字表示数字?

algorithm - 按心情分桶句子

c - 如何找到对列表中所有有重叠的对?