【问题标题】:What is the time complexity of this (simple) code?这个(简单)代码的时间复杂度是多少?
【发布时间】:2013-10-05 01:18:27
【问题描述】:

我正在尝试计算下面代码的运行时间,无论列表是数组列表还是链接列表。我很感激任何建议!

数组:我认为删除操作是 O(n),循环是 N/2,所以 O(n^2)

LinkedList:只有引用发生变化,所以移除的时间恒定,循环的时间为 N/2,所以 O(n)

int halfSize = lst.size() / 2;

for (int i = 0; i < halfSize; i++){
    lst.remove(0);
}

【问题讨论】:

  • 这个问题似乎离题了,因为它是关于代码复杂性的。
  • @ColeJohnson Borderline 在这里可以接受,我不认为密切投票是为了这个原因。当然,这个问题很简单,尽管它包含了一个基本的尝试。
  • @hexafraction 程序员或代码审查会是更好的选择吗?
  • 看来您的判断是准确的:ArrayList.remove(0) 运行时间为 O(n),运行 (n/2) 次为 O(n^2)。 LinkedList.remove(0) 在 O(1) 中运行,所以这将是 O(n)。
  • @ColeJohnson 关于复杂性的问题不一定是题外话;为什么你认为我们有标签?

标签: java time complexity-theory


【解决方案1】:

数组列表: 评估正确,由于底层array copy

    public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

链表: 评估正确,节点移除@zero 索引是常数

public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}

/**
 * Returns the (non-null) Node at the specified element index.
 */
Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

【讨论】:

  • 我们从链表的头部移除,这是一个 O(1) 操作。
  • 真的...忘记了索引始终为 0。相应地进行了编辑。
  • 考虑到这一点,我认为作者的评价没有问题。
猜你喜欢
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
  • 2016-10-30
  • 2015-03-31
  • 1970-01-01
  • 2022-11-14
  • 2022-01-13
相关资源
最近更新 更多