zoukankan      html  css  js  c++  java
  • 数组和链表的时间复杂度

    数组的时间复杂度

    操作 时间复杂度
    头插(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)的方式。

  • 相关阅读:
    php openssl 加密解密
    PHP中进制之间的互相转换
    零基础学习FFMPEG
    git 强制更新本地和强制提交覆盖
    mysql 不常用备忘
    mysql <=> null 问题
    GD库imagettftext中文乱码的问题
    flex布局设置width无效
    下拉菜单css
    swagger:API在线文档自动生成框架
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/13150087.html
Copyright © 2011-2022 走看看