Reduce remove cost from O(n) to O(1)
Exchange the item with the last item in the array and then pop it.pull/469/head
parent
53c0cf7de8
commit
ab57931249
|
@ -33,6 +33,7 @@ class HashTable(object):
|
|||
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]
|
||||
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
|
||||
raise KeyError('Key not found')
|
||||
|
|
Loading…
Reference in New Issue