【问题标题】:Time complexity to get element from ArrayDeque从 ArrayDeque 获取元素的时间复杂度
【发布时间】:2018-11-27 17:17:35
【问题描述】:

我在某些地方读到,Java 中的 LinkedList 添加和删除元素的时间复杂度为 O(1),而获取元素的时间复杂度为 O(n)。而 ArrayList 有 O(1) 来获取元素和 O(n) 来添加和删除。

我有一个程序,它必须执行许多涉及从列表中插入和恢复元素的操作。所以,我想知道 ArrayDeque 访问元素的时间是否类似于 ArrayList。

【问题讨论】:

  • 您在提问之前阅读过 java 文档吗? Deque 的文档说明 大多数 ArrayDeque 操作在摊销的常数时间内运行。例外情况包括 remove、removeFirstOccurrence、removeLastOccurrence、contains、iterator.remove() 和批量操作,所有这些操作都以线性时间运行。 请参阅 docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html
  • 谢谢,这个链接太棒了,我从来没有找到过这样的东西。

标签: java data-structures time-complexity


【解决方案1】:

来自javadoc,是这样写的,

Most ArrayDeque operations run in amortized constant time. Exceptions include remove,
removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk
operations, all of which run in linear time.

所以,移除一个元素是线性时间运算,得到它应该是 O(1)。

编辑:

摊销恒定时间操作意味着大部分时间操作成本将为 O(1),除非在某些情况下可能,例如。当需要调整 ArrayDeque 的大小时。 ArrayDeque 的 javadoc 还说,

Array deques have no capacity restrictions; they grow as necessary to support usage 

因此,每当向 ArrayDeque 的末尾或开头添加新元素时,其大小都会发生变化 -> 因此,如果元素总数违反了 ArrayDeque 的容量属性,则需要调整其大小,这可能高于O(1)。但是如果你做很多这样的操作并平均时间复杂度,它会非常接近 O(1)。

【讨论】:

  • @LoneWanderer,我同意......我添加了我对摊销恒定时间的含义的解释......让我知道你的想法
猜你喜欢
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 2011-09-03
  • 2020-01-28
相关资源
最近更新 更多