Update hash_map_array.py

This commit is contained in:
marina 2023-08-07 16:35:36 -07:00 committed by GitHub
parent 85f1f87c8d
commit e01b5b5e2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,25 +3,6 @@
# author: bt3gl
class HashMap:
def __init__(self, key_space):
self.key_space = key_space
self.table = [Bucket() for _ in range(self.key_space)]
def put(self, key: int, value: int):
hash_key = key % self.key_space
self.table[hash_key].put(key, value)
def get(self, key: int):
hash_key = key % self.key_space
return self.table[hash_key].get(key)
def remove(self, key: int):
hash_key = key % self.key_space
self.table[hash_key].remove(key)
class Bucket:
def __init__(self):
@ -46,7 +27,29 @@ class Bucket:
def remove(self, key):
for i, k in enumerate(self.bucket):
if key == k[0]:
# del is an O(n) operation, as we would copy all the i: elements
# del is an O(N) operation, as we would copy all the i: elements
# to make it O(1) we could swap the element we want to remove
# with the last element in the bucket
del self.bucket[i]
class HashMap:
def __init__(self, key_space):
self.key_space = key_space
self.table = [Bucket() for _ in range(self.key_space)]
def put(self, key: int, value: int):
hash_key = key % self.key_space
self.table[hash_key].put(key, value)
def get(self, key: int):
hash_key = key % self.key_space
return self.table[hash_key].get(key)
def remove(self, key: int):
hash_key = key % self.key_space
self.table[hash_key].remove(key)