簡體   English   中英

java ArrayList 的時間復雜度

[英]Time complexity for java ArrayList

ArrayList 是ArrayList的數組還是列表? get 操作的時間復雜度是多少,是O(n)還是O(1)

Java 中的ArrayList是由array支持的List

get(index)方法是一個常數時間, O(1) ,操作。

ArrayList.get(index)的 Java 庫中的代碼:

public E get(int index) {
    RangeCheck(index);
    return (E) elementData[index];
}

基本上,它只是直接從支持數組中返回一個值。 RangeCheck(index) )也是常數時間)

它的實現是用一個數組完成的,get 操作是 O(1)。

javadoc 說:

size、isEmpty、get、set、iterator 和 listIterator 操作在恆定時間內運行。 , that is, adding n elements requires O(n) time. add 操作在運行,即添加 n 個元素需要 O(n) 時間。 所有其他操作都在線性時間內運行(粗略地說)。 與 LinkedList 實現相比,常量因子較低。

正如每個人已經指出的那樣,讀取操作是恆定時間 - O(1) 但寫入操作有可能耗盡后備數組中的空間、重新分配和復制 - 因此運行時間為 O(n) ,正如文檔所說:

size、isEmpty、get、set、iterator 和 listIterator 操作在恆定時間內運行。 add 操作在分攤常數時間內運行,即添加 n 個元素需要 O(n) 時間。 所有其他操作都在線性時間內運行(粗略地說)。 與 LinkedList 實現相比,常量因子較低。

實際上,在添加幾次之后,一切都是 O(1),因為每次其容量耗盡時,后備數組都會加倍。 所以如果數組從 16 開始,變滿了,它會被重新分配到 32,然后是 64、128 等等。所以它可以擴展,但是 GC 可能會在大的重新分配期間出現。

迂腐,它是一個由數組支持的List 是的, get()的時間復雜度是 O(1)。

只是一個注釋。

get(index)方法是一個常數時間, O(1)

但是如果我們知道索引就是這種情況。 如果我們嘗試使用indexOf(something)獲取索引,那將花費O(n)

arraylist 基本上是數組的一個實現。 所以 CRUD 操作的時間復雜度為:

get/read :  O(1) since you can seek the address directly from base

remove/delete : O(n) why ? Because once we delete the element at index, then we need to move the after values one by one to the left. 

add : O(1) becuase you always add the end of the array - next free address available.

update : O(1) since you are just changing the value but nothing value moving....across the array.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM