最佳查找数据结构,仅存储密钥(无值字典)

Luc*_*ano 4 c# collections dictionary data-structures

.Net中具有高性能查找的最佳数据结构是什么,如二叉树实现,但只存储密钥(字符串键)?

我们只需要检查集合中是否存在某个键.喜欢:

Dictonary<string, object> myKeys;
myKeys.Add("key1", null);
myKeys.Add("key2", null);
// Dozens or hundreds keys

Assert.IsTrue(myKeys.Contains("key1")); 
Run Code Online (Sandbox Code Playgroud)

Mit*_*eat 14

A HashSet(in System.Collections.Generic):

HashSet是一个包含唯一元素的无序集合.它具有标准的集合操作Add,Remove,Contains,但由于它使用基于散列的实现,因此这些操作是O(1).

例如

    HashSet<int> evenNumbers = new HashSet<int>();
    HashSet<int> oddNumbers = new HashSet<int>();

    for (int i = 0; i < 5; i++)
    {
        // Populate numbers with just even numbers.
        evenNumbers.Add(i * 2);

        // Populate oddNumbers with just odd numbers.
        oddNumbers.Add((i * 2) + 1);
    }

    if (evenNumbers.Contains(2))
    {
        Console.WriteLine("2 is even.");
    }
Run Code Online (Sandbox Code Playgroud)

  • @Luciano:如果您查看 [HashSet.Add](http://msdn.microsoft.com/en-us/library/bb353005.aspx) 和 [HashSet.Contains](http://msdn.microsoft. com/en-us/library/bb356440.aspx)(以及其他方法),您将看到描述算法复杂性的注释。特别是,`Contains` 是 O(1),而 `Add` 是 O(1),只要不需要调整内部数组的大小。 (2认同)