对象 ArrayList 中 contains(Object o) 的时间复杂度
正如标题所说,我想知道 ArrayList
是。
As the title says, I was wondering what the time complexity of the contains()
method of an ArrayList
is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
http://download.oracle.com/javase/6 /docs/api/java/util/ArrayList.html
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
ArrayList 的 O(n)
it's O(n) for ArrayList
如果您查看 ArrayList 的源代码并检查其
contains
方法,它看起来如下所示:contains
将检查委托给indexOf方法。因此,如果我们检查
indexOf
实现,它如下所示:从代码中可以看出,为了找到给定元素的索引,在最坏的情况下,必须迭代整个阵列。随着数组大小的增加,元素的搜索时间也会增加。因此,
contains
方法的时间复杂度为O(n)
,其中n
是列表中元素的数量。If you look into the source code for
ArrayList
and check itscontains
method it looks as below:contains
delegates the check to theindexOf
method. So, if we check theindexOf
implementation it is as follows:As it can be seen from the code, in order to find an index of a given element, one, in the worst case, must iterate through the whole array. As a size of the array grows and so does the search time by an element. Hence, the time complexity of
contains
method isO(n)
, wheren
is the number of elements in the list.它的
O(n)
。contains(Object o)
在indexOf()
上实现,需要O(n)
。因此contains(Object o)
的复杂性是防御性的O(n)
如果您需要的话,这里还有其他一些:
its
O(n)
.contains(Object o)
is implemented onindexOf()
which takesO(n)
. So complexity ofcontains(Object o)
is defensivelyO(n)
Here are some other if you need: