Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.app
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.code
用一個隊列存放當前的元素,用字典結構表示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