数据类型:链表
**时间复杂度:**O(1)
**空间复杂度:**O(N)
代码实现:
python
class Node:
def __init__(self, key=-1, value=-1):
self.key = key
self.val = value
self.next = None
self.prev = None
class LRUCache:
def __init__(self, capacity: int):
self.map = dict()
self.cap = capacity
self.left = Node()
self.right = Node()
self.right.prev = self.left
self.left.next = self.right
def pop(self, node: Node):
node.prev.next, node.next.prev = node.next, node.prev
def push(self, node: Node):
last = self.right.prev
last.next = node
node.prev, node.next = last, self.right
self.right.prev = node
def get(self, key: int) -> int:
if key not in self.map: return -1
self.pop(self.map[key])
self.push(self.map[key])
return self.map[key].val
def put(self, key: int, value: int) -> None:
if key in self.map:
self.pop(self.map[key])
elif self.cap == len(self.map):
self.map.pop(self.left.next.key)
self.pop(self.left.next)
self.push(Node(key, value))
self.map[key] = self.right.prev
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)