【问题标题】:C# has no SortedList<T>?C# 没有 SortedList<T>?
【发布时间】:2017-06-13 21:55:44
【问题描述】:

我正在尝试解决一个问题,在该问题中拥有像

这样的数据结构会很有用
var list = new SortedList<int>(); 
list.Add(3); // list = { 3 } 
list.Add(1); // list = { 1, 3 }
list.Add(2); // list = { 1, 2, 3 }
int median = list[list.Length / 2];

  • O(n) 次插入
  • O(1) 按索引查找

但我看不出有这样的东西存在?我看到有一些令人困惑的SortedList&lt;T,U&gt;,然后是一个界面SortedList,但这些都不是我想要的。

【问题讨论】:

标签: c# .net algorithm data-structures


【解决方案1】:

.NET 框架中的排序列表是一个关联列表(即用于键/值对)。如果您使用二进制搜索功能,则可以使用常规的List&lt;T&gt;,如果您始终保持列表排序,则该功能有效。您可以将其封装在扩展方法中:

static class SortedListExtensions {
    public static void SortedAdd<T>(this List<T> list, T value) {
        int insertIndex = list.BinarySearch(value);
        if (value < 0) {
            value = ~value;
        }
        list.Insert(insertIndex, value);
    }

    //Added bonus: a faster Contains method
    public static bool SortedContains<T>(this List<T> list, T value) {
        return list.BinarySearch(value) >= 0;
    }
}


List<int> values = new List<int>();
values.SortedAdd(3);
values.SortedAdd(1);
values.SortedAdd(2);

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 2010-09-28
    • 1970-01-01
    • 2010-11-09
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2012-02-02
    相关资源
    最近更新 更多