我使用了很多列表和数组,但我还没有遇到一个场景,数组列表不能像链表一样容易使用,如果不是更容易的话。我希望有人能给我一些例子,说明什么时候链表明显更好。
当前回答
在现实中,内存局部性对实际处理的性能有很大的影响。
与随机访问相比,磁盘流在“大数据”处理中的使用越来越多,这表明围绕它构建应用程序可以在更大范围内显著提高性能。
如果存在按顺序访问数组的方法,则这是迄今为止性能最好的方法。如果性能很重要,那么至少应该考虑将此作为设计目标。
其他回答
这些是最常用的Collection实现。
数组列表:
插入/删除在结尾一般O(1)最坏情况O(n) 中间插入/删除O(n) 检索任意位置O(1)
LinkedList:
在任何位置O(1)插入/删除(注意你是否引用了元素) 中间检索O(n) 检索第一个或最后一个元素O(1)
向量:不要用。它是一个类似于ArrayList的旧实现,但所有方法都是同步的。对于多线程环境中的共享列表,这不是正确的方法。
HashMap
在O(1)中按键插入/删除/检索
TreeSet 插入/删除/包含O(log N)
HashSet 在O(1)中插入/删除/包含/大小
如果您需要在中间插入项,并且不想开始调整数组大小和移动内容,则列表的优势就会显现出来。
你是对的,通常情况下并非如此。我遇到过一些非常具体的案例,但不是很多。
Algorithm ArrayList LinkedList
seek front O(1) O(1)
seek back O(1) O(1)
seek to index O(1) O(N)
insert at front O(N) O(1)
insert at back O(1) O(1)
insert after an item O(N) O(1)
数组列表适用于写一次读多次或追加程序,但不适用于从前面或中间进行添加/删除。
这完全取决于你在迭代时所做的操作类型,所有数据结构都在时间和内存之间进行权衡,我们应该根据需要选择正确的DS。有些情况下,LinkedList比数组快,反之亦然。考虑数据结构上的三个基本操作。
搜索
由于array是基于索引的数据结构,搜索array.get(index)将花费O(1)时间,而linkedlist不是索引DS,因此您将需要遍历到index,其中index <=n, n是链表的大小,因此array在随机访问元素时比链表更快。
那么,这背后有什么好处呢?
As Arrays are contiguous memory blocks, large chunks of them will be loaded into the cache upon first access this makes it comparatively quick to access remaining elements of the array,as much as we access the elements in array locality of reference also increases thus less catch misses, Cache locality refers to the operations being in the cache and thus execute much faster as compared to in memory,basically In array we maximize the chances of sequential element access being in the cache. While Linked lists aren't necessarily in contiguous blocks of memory, there's no guarantee that items which appear sequentially in the list are actually arranged near each-other in memory, this means fewer cache hits e.g. more cache misses because we need to read from memory for every access of linked list element which increases the time it takes to access them and degraded performance so if we are doing more random access operation aka searching , array will be fast as explained below.
插入
这是简单和快速的LinkedList的插入是O(1)操作在LinkedList (Java)阵列相比,考虑数组充满的情况下,我们需要将内容复制到新数组如果数组完全使一个元素插入ArrayList O (n)在坏的情况下,而ArrayList还需要更新其指数年底如果你插入一些除了数组,链表的我们不必调整它,你只需要更新指针。
删除
它的工作原理类似于插入,在LinkedList中比在array中更好。
数组具有O(1)随机访问,但是向数组中添加或删除内容的代价非常高。
链表在任何地方添加或删除项目和迭代都非常便宜,但随机访问是O(n)。
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- Linq选择列表中存在的对象(A,B,C)
- 如何在Python中将十六进制字符串转换为字节?
- 返回大列表中每n项的python方式
- 与push()相反;
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Python:查找列表中的元素
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- 如何将字典列表合并为一个字典?
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 在Python中创建一个初始容量的列表
- 如何排序一个数组列表在Java
- 在$.ajax()中将数组传递给ajax请求