【问题标题】:In an ArrayList if an element is removed at index 0 using remove(), then what will be the time complexity?在 ArrayList 中,如果使用 remove() 删除索引 0 处的元素,那么时间复杂度是多少?
【发布时间】:2021-01-25 17:51:56
【问题描述】:

我认为时间复杂度将是 O(1)。由于 remove 方法的声明中没有循环。如果我考虑时间复杂度的方法不正确,请告诉我。

remove() 的声明:

public synchronized E remove(int index) 
{
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = elementData(index);

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

    return oldValue;
}

【问题讨论】:

    标签: java data-structures


    【解决方案1】:

    这是不正确的。那里有一个循环,即使你没有看到“for”或“while”这个词。 (提示:该函数内部调用的所有函数的时间复杂度是多少?)

    【讨论】:

    • 所以即使元素从第 0 个索引中移除,时间复杂度也会是 O(N),对吧?
    • 特别是如果它是从前面移除的。这是删除元素的最糟糕的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多