Mar*_*son 47 java size linked-list time-complexity
正如标题所示,我想知道LinkedList类中的size()方法是否需要分摊O(1)时间或O(n)时间.
Gre*_*nie 63
这是O(1).你可以谷歌搜索源代码,你会得到这样的:
来自http://www.docjar.com/html/api/java/util/LinkedList.java.html
我看过的所有Collection类都将大小存储为变量,并且不会遍历所有内容来获取它.
Kri*_*ris 17
正如你所发现的O(1)你看过源代码了......
来自LinkedList:
private transient int size = 0;
Run Code Online (Sandbox Code Playgroud)
...
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
Run Code Online (Sandbox Code Playgroud)