數組的時間復雜度
操作 | 時間復雜度 |
頭插(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)的方式。