mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update hash_map_array.py
This commit is contained in:
parent
85f1f87c8d
commit
e01b5b5e2a
@ -3,25 +3,6 @@
|
|||||||
# author: bt3gl
|
# 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:
|
class Bucket:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -46,7 +27,29 @@ class Bucket:
|
|||||||
def remove(self, key):
|
def remove(self, key):
|
||||||
for i, k in enumerate(self.bucket):
|
for i, k in enumerate(self.bucket):
|
||||||
if key == k[0]:
|
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
|
# to make it O(1) we could swap the element we want to remove
|
||||||
# with the last element in the bucket
|
# with the last element in the bucket
|
||||||
del self.bucket[i]
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user