【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.

解题思路:

用一个队列存放当前的元素,用字典结构表示cache

#coding=utf-8
class LRUCache:

    # @param capacity, an integer
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.sta = []
        
    # @return an integer
    def get(self, key):
        if key in self.cache:
            self.sta.remove(key)
            self.sta.append(key)
            return self.cache[key]
        else:
            return -1

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        if self.cap == len(self.cache) and (key not in self.cache):
            self.cache.pop(self.sta[0])
            self.sta.pop(0)
        if key in self.cache:
            self.sta.remove(key)
            self.sta.append(key)
        else:
            self.sta.append(key)
        self.cache[key] = value
posted @ 2015-02-10 13:05  mrbean  阅读(263)  评论(0编辑  收藏  举报