设置key -value的dic,然后用value作为que的index,储存valid time。剩下的按照题目要求来就好,注意ttl是0的时候que对应的位置的时间设置为float(‘inf’)
class Memcache:
def __init__(self):
# do intialization if necessary
self.dic = collections.defaultdict()
self.que = [float('-inf')]*100010
"""
@param: curtTime: An integer
@param: key: An integer
@return: An integer
"""
def get(self, curtTime, key):
# write your code here
if key not in self.dic:return 2147483647
if self.que[self.dic[key]] < curtTime:
self.delete(curtTime, key)
return 2147483647
return self.dic[key]
"""
@param: curtTime: An integer
@param: key: An integer
@param: value: An integer
@param: ttl: An integer
@return: nothing
"""
def set(self, curtTime, key, value, ttl):
# write your code here
if key in self.dic:
self.que[self.dic[key]] = float('-inf')
self.dic[key] = value
if ttl != 0:
self.que[value] = curtTime + ttl - 1
else:
self.que[value] = float('inf')
"""
@param: curtTime: An integer
@param: key: An integer
@return: nothing
"""
def delete(self, curtTime, key):
# write your code here
self.que[self.dic[key]] = float('-inf')
del self.dic[key]
"""
@param: curtTime: An integer
@param: key: An integer
@param: delta: An integer
@return: An integer
"""
def incr(self, curtTime, key, delta):
# write your code here
if key not in self.dic:return 2147483647
valueoftime = self.que[self.dic[key]]
self.que[self.dic[key]] = float('-inf')
self.dic[key] += delta
self.que[self.dic[key]] = valueoftime
return self.dic[key]
"""
@param: curtTime: An integer
@param: key: An integer
@param: delta: An integer
@return: An integer
"""
def decr(self, curtTime, key, delta):
# write your code here
if key not in self.dic:return 2147483647
valueoftime = self.que[self.dic[key]]
self.que[self.dic[key]] = float('-inf')
self.dic[key] -= delta
self.que[self.dic[key]] = valueoftime
return self.dic[key]