问题描述
这与 Equivalent of Java's SortedMap.tailMap in C# SortedDictionary 有关,但我的要求略有不同,所以我希望可能有更好的解决方案。
我有一个 SortedDictionary,我有一个键值 K,它在字典中不存在。我想找到存在于 K 之上和之下最近的键。
通过 Java TreeMap,我可以使用 floorKey() 和 purgeKey() 方法来做到这一点。
我知道我可以有效地获取字典中已排序的键列表,但这似乎对我没有帮助。
(a) 有没有办法用 SortedDictionary 有效地做到这一点?
(b) 如果没有,我可以使用不同的集合类吗? (我显然也需要 SortedDictionary 的标准功能)
解决方法
Array.BinarySearch(...) 听起来像你想要的。 https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=net-5.0
以下是查找小于指定项的最大项的示例。
T[] array = ...; // array must be sorted and T must implement IComparable<T>
T item = ...; // item that you are trying to find in array
int index = Array.BinarySearch(array,item);
if (index < 0)
{
// item not found
// index represents the bitwise complement of the next larger element in the array
index = ~index;
if (index == 0)
{
// specified item is less than the smallest item in the array
}
else
{
// array[index - 1] is the largest item that is less than the specified item
}
}
else
{
// array[index] is the specified item
}