146 LRU

这道题需要用到python中的 OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.dict = collections.OrderedDict()
        self.capacity = capacity
        self.len = 0

    def get(self, key):
        if key in self.dict:
            value = self.dict[key]
            del self.dict[key]
            self.dict[key] = value
            return value
        else:
            return -1

    def set(self, key, value):
        if key in self.dict:
            del self.dict[key]
            self.dict[key] = value
        else:
            if self.len == self.capacity:
                self.dict.popitem(last = False)
                self.len -= 1
            self.dict[key] = value
            self.len += 1

 

posted @ 2015-07-09 12:42  dapanshe  阅读(89)  评论(0编辑  收藏  举报