题目描述：

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

题目大意：

get(key) - 取值(key恒为正), 不存在时返回-1。
set(key, value) - 设置或者插入值（如果key不存在时）。 如果缓存达到容量上限，它应该在插入新元素前移除近期最少使用的元素。

Python代码：

``````# Definition for a doubly-linked list node
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None

class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.dummyNode = Node(-1, -1)
self.tail = self.dummyNode
self.entryFinder = {}

# @return an integer
def get(self, key):
entry = self.entryFinder.get(key)
if entry is None:
return -1
else:
self.renew(entry)
return entry.val

# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
entry = self.entryFinder.get(key)
if entry is None:
entry = Node(key, value)
self.entryFinder[key] = entry
self.tail.next = entry
entry.prev = self.tail
self.tail = entry
if self.size < self.capacity:
self.size += 1
else:
else:
entry.val = value
self.renew(entry)

def renew(self, entry):
if self.tail != entry:
prevNode = entry.prev
nextNode = entry.next
prevNode.next = nextNode
nextNode.prev = prevNode
entry.next = None
self.tail.next = entry
entry.prev = self.tail
self.tail = entry
``````

OrderedDict有序字典法：（Accepted 320ms）

``````class LRUCache:

# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.cache = collections.OrderedDict()

# @return an integer
def get(self, key):
if not key in self.cache:
return -1
value = self.cache.pop(key)
self.cache[key] = value
return value

# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if key in self.cache:
self.cache.pop(key)
elif len(self.cache) == self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
``````

Pingbacks已关闭。