Reduce remove cost from O(n) to O(1)

Exchange the item with the last item in the array and then pop it.
This commit is contained in:
john-the-dev
2020-09-10 01:51:02 -07:00
committed by GitHub
parent 53c0cf7de8
commit ab57931249

View File

@@ -33,6 +33,7 @@ class HashTable(object):
hash_index = self._hash_function(key) hash_index = self._hash_function(key)
for index, item in enumerate(self.table[hash_index]): for index, item in enumerate(self.table[hash_index]):
if item.key == key: if item.key == key:
del self.table[hash_index][index] self.table[hash_index][index],self.table[hash_index][-1] = self.table[hash_index][-1],self.table[hash_index][index]
self.table[hash_index].pop()
return return
raise KeyError('Key not found') raise KeyError('Key not found')