问题诱因:https://leetcode.com/submissions/detail/481019484/中,Deque<String> l1 = new ArrayDeque<>(Arrays.asList(sentence1.split(" ")));
用到了ArrayDeque而不是LinkedList。为什么?
LinkedList | ArrayDeque | |
---|---|---|
数据结构 | 带头尾结点的双向链表 | 长度为2的幂的环形数组1 |
读取效率 | 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.2 | |
元素可否为null | 可 | 不可 |
题目中,对Deque的操作主要是去除头尾元素。因为ArrayDeque用的是环形数组,所以即使是读/操作数组头,也不会像ArrayList那样引发其它数组元素的移动,即时间复杂度是O(1)而非O(n)。所以在此题中,即使从效率考虑,可以使用ArrayDeque。在效率方面,LinkedList优于ArrayDeque的唯一操作,应该是随机删。相同观点可见于https://stackoverflow.com/a/6163204/14993533