gpt4 book ai didi

java - 为什么 AbstractList.removeRange 需要二次时间?

转载 作者:行者123 更新时间:2023-11-29 06:41:11 26 4
gpt4 key购买 nike

我可以在文档中看到:

java.util.AbstractList#removeRange

它需要二次时间:

This implementation gets a list iterator positioned before fromIndex, and repeatedly calls ListIterator.next followed by ListIterator.remove until the entire range has been removed. Note: if ListIterator.remove requires linear time, this implementation requires quadratic time.

但是为什么??代码:

protected void removeRange(int fromIndex, int toIndex) {
ListIterator<E> it = listIterator(fromIndex);
for (int i=0, n=toIndex-fromIndex; i<n; i++) {
it.next();
it.remove();
}
}

对我来说似乎是线性的...但我一定是错的,因为我是这类算法方面的新手。请帮助我理解它。

最佳答案

重要的部分是“注意:如果 ListIterator.remove 需要线性时间,则此实现需要二次时间。” for 循环需要线性时间,你是对的。但是,如果您在每次迭代中执行线性时间步长,您将得到 n * n = n^2

关于java - 为什么 AbstractList.removeRange 需要二次时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11810997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com