Article Directory
setAll hash table
Unified hash table settings
[Title]
hash table put
, get
and the containsKey
time complexity of the three operations is O (1).
Now add setAll
operation: the value of all the records are set to a uniform value, and the required time complexity is O (. 1) .
Algorithm thinking
Each value is immediately set to unity, must traverse the entire path hash table, the time complexity is O (N),
the subject of the request setAll
operation time complexity is O (1).
Therefore conceivable to use a timestamp, each unified setting is constant, just get
when the comparison operation is stored in the hash table value time and the setAll
time of the operation, that can obtain a value (a value near the logic behind the time for the true value).
Essentially a delay operation , the setAll
operation of the set value of the time dispersion into get
operation the comparison time in. Thus the real data and the data stored in the hash table inconsistencies (possibly setAll
the value).
Corresponding code
# 给存储的value和setAll操作加上时间戳,比较时间判断之前的存储的value是否受到setAll操作影响
# 通过延迟操作,将setAll操作的时间分散到get的时间判断中
class MyValue():
def __init__(self, value, time):
self.value = value
self.time = time
def get_value(self):
return self.value
def get_time(self):
return self.time
class MyHashMap():
def __init__(self):
self.map = {}
self.time = 0
self.set_all = MyValue(-1, self.time)
def put(self, key, value):
self.time += 1
self.map[key] = MyValue(value, self.time)
def get(self, key):
self.time += 1
if self.map[key].get_time() < self.set_all.get_time():
return self.set_all.get_value()
else:
return self.map[key].get_value()
def containsKey(self, key):
self.time += 1
return key in self.map
def setAll(self, value):
self.time += 1
self.set_all = MyValue(self.time, value)
Have any questions or suggestions, please leave a message in the comments section and correct me!
We appreciate the time and effort you spend!