mirror of
https://github.com/donnemartin/system-design-primer.git
synced 2025-09-17 09:30:39 +03:00
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:
@@ -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')
|
||||
|
Reference in New Issue
Block a user