假设我有一组固定的数字,并且恰好已排序:
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/