常用資料結構的時間複雜度
程式的複雜度分為時間複雜度和空間複雜度,通過字面上可以看出它們的含義,下面我們主要來看一個集合的時間複雜度,這些集合基本包含了.net裡的所有了,呵呵!
Data Structure | Add | Find | Delete | GetByIndex |
Array (T[]) |
O(n) |
O(n) |
O(n) |
O(1) |
Linked list (LinkedList<T>) |
O(1) |
O(n) |
O(n) |
O(n) |
Resizable array list (List<T>) |
O(1) |
O(n) |
O(n) |
O(1) |
Stack (Stack<T>) |
O(1) |
- |
O(1) |
- |
Queue (Queue<T>) |
O(1) |
- |
O(1) |
- |
Hash table (Dictionary<K,T>) |
O(1) |
O(1) |
O(1) |
- |
Tree-based dictionary (SortedDictionary<K,T>) |
O(log n) |
O(log n) |
O(log n) |
- |
Hash table based set (HashSet<T>) |
O(1) |
O(1) |
O(1) |
- |
Tree based set (SortedSet<T>) |
O(log n) |
O(log n) |
O(log n) |
- |
如何選擇資料結構
Array (T[])
- 當元素的數量是固定的,並且需要使用下標時。
Linked list (LinkedList<T>)
- 當元素需要能夠在列表的兩端新增時。否則使用 List<T>。
Resizable array list (List<T>)
- 當元素的數量不是固定的,並且需要使用下標時。
Stack (Stack<T>)
- 當需要實現 LIFO(Last In First Out)時。
Queue (Queue<T>)
- 當需要實現 FIFO(First In First Out)時。
Hash table (Dictionary<K,T>)
- 當需要使用鍵值對(Key-Value)來快速新增和查詢,並且元素沒有特定的順序時。
Tree-based dictionary (SortedDictionary<K,T>)
- 當需要使用鍵值對(Key-Value)來快速新增和查詢,並且元素根據 Key 來排序時。
Hash table based set (HashSet<T>)
- 當需要儲存一組唯一的值,並且元素沒有特定順序時。
Tree based set (SortedSet<T>)
- 當需要儲存一組唯一的值,並且元素需要排序時。
鳴謝
本文原文由Dennis Gao 發表自部落格園,本人只是收藏之
本文章來自:http://www.cnblogs.com/gaochundong/p/3813252.html
相關參考資料: