[LeetCode]LRU Cache

题目描述:

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.

题目大意:

设计并实现近期最少使用(LRU)缓存的数据结构。它应该支持下面的操作:get和set。

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

解题思路:

双向链表(Doubly-Linked List) + 字典(Dict)

或者使用Python的OrderedDict有序字典

Python代码:

双向链表法:(Accepted 282ms)

# 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:
                headNode = self.dummyNode.next
                if headNode is not None:
                    self.dummyNode.next = headNode.next
                    headNode.next.prev = self.dummyNode
                del self.entryFinder[headNode.key]
        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)

代码非常简洁,参考链接:https://oj.leetcode.com/discuss/12536/very-short-solution-using-pythons-ordereddict

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

 

本文链接:http://bookshadow.com/weblog/2015/01/08/leetcode-lru-cache/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论