List<Item> items = new ArrayList<Item>(); List<Item> lessItems = new ArrayList<Item>(); for(int index = 0; index < items.size(); index++){ Item tocheck = items.get(i); if(tocheck meets some condition){ lessItems.add(tocheck); } }
我不确定这里的时间复杂程度.我在所有项目上调用get(),这样就是O(n).然后我也在潜在的所有项目上调用add(),所以还有另一个O(n).这个不太确定.
解决方法
>迭代项列表的第一个循环:复杂度为O(n)
>将每个项目插入列表末尾lessItems:在正常数组中,它将是其他人所说的O(n).但Java使用amortized array为ArrayList实现.这意味着当在数组末尾插入时,算法仅花费Amortized O(1).或者你可以说O(1)
因此,代码的复杂性为:O(n)*摊销O(1).简而言之就是O(n)
另一个参考:
附加说明1:
如果在阵列末尾插入的复杂度是O(N),那么总复杂度是O(N ^ 2),而不是其他答案所说的O(2 * N).因为插入的总复杂度将是:1 2 3 … n = n *(n 1)/ 2
附加说明2:
The size,isEmpty,get,set,iterator,and listIterator operations run
in constant time. The add operation runs in amortized constant time,
that is,adding n elements requires O(n) time. All of the other
operations run in linear time (roughly speaking). The constant factor
is low compared to that for the LinkedList implementation.
附加说明3:
private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscIoUs code if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscIoUs code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size,so this is a win: elementData = Arrays.copyOf(elementData,newCapacity); }
正如源代码所说,当程序添加使数组大小大于当前容量的元素时,Array将会增长.增长阵列的新大小将是:
int newCapacity = oldCapacity + (oldCapacity >> 1);
这是一个使插入分摊的技巧O(1)