雜湊表(hash)
阿新 • • 發佈:2019-01-05
C++ hash
STL c++ hash_table 分析
簡介
- 由索引到值的資料結構(data structure that maps keys to values)
- 直接對映,需要很大的空間。空間的利用率不高,為了將某一元素對映到一個“大小可以接受之索引”,這樣的函式為hash function(雜湊函式或者雜湊函式)。通常的雜湊函式為取模。
雜湊函式(hash function)
h(key) => hash table index
好的雜湊函式特點
- 易於計算
- 分佈均勻(Reduce chance of collision)
- different keys should ideally map to different indices
- distribute keys uniformly over table
複雜度(complexity)
- 最好情況O(1)查詢
- 最壞情況O(N)發生了衝突(collisions)
對於string型別雜湊函式的設計
- 簡單的ASCII碼值相加,隱患很大
- 使用前三個字元,以27為基,計算key值
- 使用所有字元,以比字元個數大的質數為基。26個字母,則選擇,29,31,37
解決衝突的辦法
- 分離鏈路(Chaining):在雜湊表索引同樣的地方,以連結串列的形式儲存value
- 開放地址(Open addressing):
- 二次雜湊(double hash)