码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] LRU Cache @ Python

时间:2014-09-16 03:53:49      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   for   

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.

 

思路分析:可以考虑利用dict数据结构,查找时间是O(1)。但是Python的dictionary缺点是无序。而collections.OrderedDict是有序的, 后加入的元素一定排在先加入元素的后面, 操作和dictionary类似。所以本题目将利用此有序dictionary数据结构来实现。

作为背景知识,请复习:

import collections
a = collections.OrderedDict()
a[1] = 10 # 若1在a中就更新其值, 若1不在a中就加入(1, 10)这一对key-value。
a[2] = 20
a[3] = 30
del a[2]
a.popitem(last = True) # 弹出尾部的元素
a.popitem(last = False) # 弹出头部的元素

 

代码如下:

class LRUCache:
    # @param capacity, an integer
    def __init__(self, capacity):
        LRUCache.capacity = capacity
        LRUCache.length = 0
        LRUCache.dict = collections.OrderedDict()

    # @return an integer        
    def get(self, key):
        try:
            value = LRUCache.dict[key]
            del LRUCache.dict[key]
            LRUCache.dict[key] = value
            return value
        except:
            return -1
            
    # @param key, an integer
    # @param value, an integer
    # @return nothing        
    def set(self, key, value):
        try:
            del LRUCache.dict[key]
            LRUCache.dict[key] = value
        except:
            if LRUCache.length == LRUCache.capacity:
                LRUCache.dict.popitem(last = False)
                LRUCache.length -= 1
            LRUCache.dict[key] = value
            LRUCache.length +=1

参考致谢:

[1]http://chaoren.is-programmer.com/posts/43116.html

[2]http://www.cnblogs.com/zuoyuan/p/3701572.html  (这个代码有75行,面试时效很差;但是是很好的对双向链表的练习)

[leetcode] LRU Cache @ Python

标签:des   style   blog   http   color   io   os   ar   for   

原文地址:http://www.cnblogs.com/asrman/p/3974089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!