Why is the time complexity of python's list.append() method O(1)?

前端 未结 3 655
难免孤独
难免孤独 2020-12-04 23:55

As seen in the documentation for TimeComplexity, Python\'s list type is implemented is using an array.

So if an array is being used and we do a few appe

3条回答
  •  眼角桃花
    2020-12-05 00:32

    This is very easy.

    We can calculate this by accumulating the total time of appending n elements into an arraylist and divide it by n.

    Firstly, we need to relocate log(n) times, and every relocation is doubled by 2.So we have a proportional series whose ratio is 2, and the length is log(n).

    The sum of a proportional series is a(1-r^n)/(1-r) So the total time of relocation is (1-n)/(1-2)=n The time complexity would be n/n=1.

提交回复
热议问题