数组和链表的时间复杂度

数组的时间复杂度

 

操作 时间复杂度
头插(vector没有此操作) O(1)
push_back O(1)
insert O(n)
erase O(n)
随机访问 O(1)

 

链表的时间复杂度

操作 时间复杂度
push_front(头插) O(1)
push_back O(1)
insert O(1)
erase O(1)

随机访问

O(n)

 

如何理解vector的erase的时间复杂度是o(n)?

因为vector底层是连续的数组,因此erase之后需要重新分配空间,它的时间等于删除元素的时间加上剩下的元素移动的时间.

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

 

Complexity:Linear on the number of elements erased (destructions) plus the number of elements after the last element deleted (moving).

与(被删除(析构操作)元素的个数+剩余元素的个数(移动操作))成正比.即为o(n)

英文来源:http://www.cplusplus.com/reference/vector/vector/erase/

 

 

如何理解随机访问?

例如vector,iterator i = v.begin()+N,得到第N+1个元素的迭代器。可以直接通过+N的方式跳到要访问的位置。

而list不是随机访问,想要到第N+1个元素位置,需要一个一个遍历,才能找到,因此不能够用+N的方法。需要使用advance(i, N)的方式。

posted @ 2020-06-17 00:47  心媛意码  阅读(2140)  评论(0编辑  收藏  举报