What is the time complexity of adding an element at the beginning of an ArrayList?

后端 未结 4 1126
Happy的楠姐
Happy的楠姐 2021-02-13 19:32

Say I have a ArrayList with n element in this array, and I add an element at the beginning:

myArrayList.add(0,\'some value\');

What will be the

4条回答
  •  一向
    一向 (楼主)
    2021-02-13 19:50

    • Building the list from scratch and adding lots of elements to the beginning runs in quadratic time: O(n2).
    • Adding all elements to the end of the list and then calling Collections.reverse(list) runs in linear time: O(n).

提交回复
热议问题