【问题标题】:Get nearest key above or below in a C# SortedDictionary [duplicate]在C#SortedDictionary中获取上方或下方最近的键[重复]
【发布时间】:2021-05-06 08:23:08
【问题描述】:

这与Equivalent of Java's SortedMap.tailMap in C# SortedDictionary有关,但我的要求略有不同,所以我希望可能有更好的解决方案。

我有一个 SortedDictionary,并且我有一个键值 K,它不在字典中。我想找到存在的 K 上方和下方最近的键。

使用 Java TreeMap,我可以使用 floorKey() 和 ceilingKey() 方法来做到这一点。

我知道我可以有效地获取字典中存在的键的排序列表,但这似乎对我没有帮助。

(a) 有没有办法使用 SortedDictionary 有效地做到这一点?

(b) 如果没有,我可以使用不同的集合类吗? (我显然也需要 SortedDictionary 的标准功能)

【问题讨论】:

  • 好吧,如果它是最新的,那么它确认没有简单的现成解决方案。 (此外,该问题正在寻找实际存在的密钥的前任,而我正在寻找不存在的密钥的前任,因此该问题中的一些建议方法不起作用。)
  • SortedDictionaryTreeSet 的包装器,SortedSet 作为具有唯一父节点的左右节点进行管理。它更像是数学理论中的集合,像链表一样有序,而不是像数组那样的列表。
  • 如果您可以改用SortedList,那么它的Keys 属性是有序的IList<TKey>,因此您可以对其执行二分查找。为了获得更好的性能(但这取决于实际用例),您也可以试试我的CircularSortedList<TKey, TValue>。请参阅docs备注部分以获取比较表,这可能有助于选择最适合您需要的类型。
  • @GyörgyKőszeg 感谢您提出使用SortedList 代替SortedDictionary 的建议。我想我可以做到。

标签: c# dictionary sorteddictionary


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2012-07-26
    • 2016-07-19
    • 2019-12-30
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多