設(shè)計一個哈希表

原文鏈接
作為演示代碼,做了以下的簡化處理:

  • 鍵類型僅支持int
  • 哈希沖突處理使用鏈存儲
  • 不設(shè)置裝載因子的處理
  • 不對輸入進行校驗
  • 默認數(shù)據(jù)大小可以完全放在內(nèi)存中
class Item(object):

    def __init__(self, key, value):
        self.key = key
        self.value = value


class HashTable(object):

    def __init__(self, size):
        self.size = size
        self.table = [[] for _ in range(self.size)]

    def _hash_function(self, key):
        return key % self.size

    def set(self, key, value):
        hash_index = self._hash_function(key)
        for item in self.table[hash_index]:
            if item.key == key:
                item.value = value
                return
        self.table[hash_index].append(Item(key, value))

    def get(self, key):
        hash_index = self._hash_function(key)
        for item in self.table[hash_index]:
            if item.key == key:
                return item.value
        raise KeyError('Key not found')

    def remove(self, key):
        hash_index = self._hash_function(key)
        for index, item in enumerate(self.table[hash_index]):
            if item.key == key:
                del self.table[hash_index][index]
                return
        raise KeyError('Key not found')

簡單說明一下,這里使用list的數(shù)據(jù)結(jié)構(gòu)存放數(shù)據(jù),哈希函數(shù)是最簡單的key值對存儲大小取余(這也是為什么key值僅支持int類型的原因)。
需要注意的幾點是,哈希函數(shù)可以選用更為通用的函數(shù),這樣就能夠支持更多的鍵數(shù)據(jù)類型;這里對于哈希沖突的解決采用了鏈式存儲,在極端條件下(即所有哈希值都映射到同一個位置),set和get方法的時間復雜度將從O(1)退化到O(n);隨著數(shù)據(jù)量的增加,哈希沖突發(fā)生的概率越來越大,所以應(yīng)當引入裝載因子進行動態(tài)擴容。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容