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
john-the-dev 2020-09-10 01:51:02 -07:00 committed by GitHub
parent 53c0cf7de8
commit ab57931249
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 2 additions and 1 deletions

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')