【问题标题】:Insert After/Before Into Sorted LinkedList Big O Complexity将 After/Before 插入已排序的 LinkedList 大 O 复杂度
【发布时间】:2018-05-22 10:32:49
【问题描述】:

在 c# 中我们有 LinkedList 库,它有一些有用的方法。其中之一是 AddAfter/AddBefore 方法。我认为在排序的 LinkedList 中,如果它使用二进制搜索,它是 O(log(n)) 复杂度;

我说得对还是你能解释得更准确

【问题讨论】:

  • 二分查找只能用于已排序的集合,插入的链表复杂度(除了先插入)是O(n)
  • docs 告诉你复杂度是 O(1)。
  • 是的,在集合中插入它是 O(1),但是如果你想在特定值之后插入,那么复杂度是多少?例如:SortedLinkedList: [2, 5, 7, 11, 14],我要插入8,基本上在11之后
  • @Lee 但未排序
  • @Boo 为什么是 O(n) 你能解释一下吗?如果我进行二分搜索

标签: c# algorithm sorting linked-list binary-search-tree


【解决方案1】:

AddBeforeAddAfter 接受LinkedListNode<> 作为第一个参数,即添加新节点之前/之后的节点。这个操作是O(1)

遍历(枚举)LinkedList 是一个 O(n) 操作,因为要查看第 x 个节点,您必须遍历 x-1 个节点。您无法对 LinkedList 进行二分搜索,因为您无法直接访问第 x 个元素而不遍历它。

因此,如果您想将新节点添加到您保持有序的LinkedList,首先您必须遍历它以找到插入新元素的“正确”位置(O(n)操作) ,那么您必须使用AddBeforeAddAfter 插入它(O(1) 操作)。复合复杂度显然是 O(n)。

【讨论】:

    【解决方案2】:

    看一下实现。这两种方法与搜索无关。所以,它是 O(1)

    public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode) {
        ValidateNode(node);
        ValidateNewNode(newNode);
        InternalInsertNodeBefore(node.next, newNode);
        newNode.list = this;
    }  
    
    public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
        ValidateNode(node);    
        ValidateNewNode(newNode);                        
        InternalInsertNodeBefore(node, newNode);
        newNode.list = this;
        if ( node == head) {
            head = newNode;
        }
    }
    
    private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
        newNode.next = node;
        newNode.prev = node.prev;
        node.prev.next = newNode;
        node.prev = newNode;            
        version++;
        count++;
    }
    

    https://github.com/Microsoft/referencesource/blob/master/System/compmod/system/collections/generic/linkedlist.cs

    【讨论】:

    • 是的,我知道在未排序的 LinkedList 中它是 O(1),但是在排序的 LinkedList 中呢?
    • 排序与否无关紧要,因为它永远不会搜索。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2023-03-30
    • 2021-05-30
    • 2013-11-18
    • 2011-09-01
    • 2021-05-13
    相关资源
    最近更新 更多