标签:wrapper 适应 hash 根据 sans oat http orm oid
class Node(object):
def __init__(self, key=None, value=None, next=None, prev=None):
self.key = key
self.value = value
self.next = next
self.prev = prev
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
# single linked list with a head node
# always put new node to the tail
# also move the revisted node to the tail
self.head = Node()
self.tail = self.head
self.head.next = self.tail
# <key, node.prev>
self.hash_table = {}
def pop_front(self):
del self.hash_table[self.head.next.key]
p_next = self.head.next.next
self.head.next = p_next
# update the reference for new front node
self.hash_table[self.head.next.key] = self.head
def append(self, node):
self.hash_table[node.key] = self.tail
self.tail.next = node
self.tail = node
def move_to_end(self, prev):
node = prev.next
if node == self.tail:
return
# disconnect node
prev.next = node.next
node.next = None
self.hash_table[prev.next.key] = prev
# append node
self.append(node)
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.hash_table:
return -1
prev = self.hash_table[key]
val = prev.next.value
self.move_to_end(prev)
return val
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.hash_table:
prev = self.hash_table[key]
prev.next.value = value
self.move_to_end(prev)
else:
self.append(Node(key, value))
if len(self.hash_table) > self.capacity:
self.pop_front()
标签:wrapper 适应 hash 根据 sans oat http orm oid
原文地址:http://www.cnblogs.com/George1994/p/7137007.html