In an ArrayList if an element is removed at index 0 using remove(), then what will be the time complexity?

huangapple go评论69阅读模式
英文:

In an ArrayList if an element is removed at index 0 using remove(), then what will be the time complexity?

问题

我认为时间复杂度将为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; // 让垃圾回收进行处理

    return oldValue;
}
英文:

I think that the time complexity will be O(1). Since there are no loops in the declaration of remove method. Please let me know if my approach to think about time complexity is incorrect.

Declaration of 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;
}

答案1

得分: 1

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

英文:

This is incorrect. There's a loop there, even if you don't see the word "for" or "while." (Hint: what are the time complexities of all the functions called inside that function?)

huangapple
  • 本文由 发表于 2020年10月11日 12:13:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64300531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定