Lecture8: Hashing Ipython
字典app
一種抽象數據類型(Abstract Data Type ,ADT),維護一組元素,每一個元素都與一個關鍵字(KEY)相關,並有如下操做:函數
實現性能
直接尋址表(Direct Access Table):用KEY爲數據下標保存元素。spa
問題:code
key必須是非負整數。ip
key的範圍不能太大。hash
解決方法:it
散列表(hashing):io
怎麼處理碰撞(collision)?
鏈接法:
把散列到同一槽中的全部元素都放在一個鏈表中。
執行性能:O(1 + α)。
python代碼:
class hashTableItem(object): def __init__(self): self.key = None self.Next = None self.val = None class hash_table_chaining(object): def __init__(self,nHashSize): self.__KeyList = [] self.__nHashSize = nHashSize for i in range(nHashSize): self.__KeyList.append(hashTableItem()) return def __HashFun(self,key): return key % self.__nHashSize def insert(self,key,val): tmpNode = self.__KeyList[self.__HashFun(key)] while( ( tmpNode.key is not None ) and ( 'deleted' != tmpNode.key ) ): tmpNode = tmpNode.Next tmpNode.key = key tmpNode.val = val tmpNode.Next = hashTableItem() return def search(self,key): tmpNode = self.__KeyList[self.__HashFun(key)] while( tmpNode.key is not None ): if key == tmpNode.key : return tmpNode.val tmpNode = tmpNode.Next return None def delete(self,key): tmpNode = self.__KeyList[self.__HashFun(key)] while( tmpNode.key is not None ): if key == tmpNode.key : tmpNode.key = 'deleted' return True tmpNode = tmpNode.Next return False
散列函數(Hash Functions)
除法散列法(Division Method): h(k) = k mod m
乘法散列法(Multiplication Method):
全域散列法(Universal Hashing):