java ArrayList 的时间复杂度
java中的ArrayList
是数组还是列表? get 操作的时间复杂度是多少,是 O(n)
还是 O(1)
?
Is ArrayList
an array or a list in java? what is the time complexity for the get operation, is it O(n)
or O(1)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Java 中的
ArrayList
是一个由数组
支持的List
。get(index)
方法是一个常数时间、O(1)
的操作。直接来自 Java 库的
ArrayList.get(index)
代码:基本上,它只是直接从支持数组中返回一个值。 (
RangeCheck(index)
) 也是常数时间)An
ArrayList
in Java is aList
that is backed by anarray
.The
get(index)
method is a constant time,O(1)
, operation.The code straight out of the Java library for
ArrayList.get(index)
:Basically, it just returns a value straight out of the backing array. (
RangeCheck(index)
) is also constant time)它的实现是通过数组完成的,并且获取操作的时间复杂度为 O(1)。
javadoc 说:
It's implementation is done with an array and the get operation is O(1).
javadoc says:
正如每个人都已经指出的那样,读取操作的时间复杂度为常数 - O(1),但写入操作有可能耗尽后备数组、重新分配和复制中的空间 - 因此运行时间为 O(n) ,正如医生所说:
实际上,经过几次添加后,一切都是 O(1),因为每次其容量耗尽时,后备数组都会加倍。因此,如果数组从 16 开始,满了,它会被重新分配到 32,然后是 64、128,等等。所以它可以扩展,但 GC 可能会在大的重新分配期间发生。
As everyone has already pointed out, read operations are constant time - O(1) but write operations have the potential to run out of space in the backing array, re-allocation, and a copy - so that runs in O(n) time, as the doc says:
In practice everything is O(1) after a few adds, since the backing array is doubled each time it's capacity is exhausted. So if the array starts at 16, gets full, it's reallocated to 32, then 64, 128, etc. so it scales okay, but GC can hit up during a big realloc.
迂腐地说,它是一个由数组支持的
List
。是的,get()
的时间复杂度是 O(1)。To be pedantic, it's a
List
backed by an array. And yes, the time complexity forget()
is O(1).只是一个注释。
get(index)
方法的时间复杂度为常数,O(1)
但如果我们知道索引,情况就是如此。如果我们尝试使用
indexOf(something)
获取索引,这将花费O(n)
Just a Note.
The
get(index)
method is a constant time,O(1)
But that's the case if we know the index. If we try to get the index using
indexOf(something)
, that will costO(n)
arraylist 基本上是数组的实现。所以对其进行 CRUD 操作的时间复杂度为:
The arraylist is basically an implementation of array. so the time complexity of the CRUD operations on it would be :