146 LRU Cache LRU緩存機(jī)制
Description:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
題目描述:
運(yùn)用你所掌握的數(shù)據(jù)結(jié)構(gòu)写烤,設(shè)計(jì)和實(shí)現(xiàn)一個 LRU (最近最少使用) 緩存機(jī)制迅腔。它應(yīng)該支持以下操作: 獲取數(shù)據(jù) get 和 寫入數(shù)據(jù) put 挚瘟。
獲取數(shù)據(jù) get(key) - 如果關(guān)鍵字 (key) 存在于緩存中恶守,則獲取關(guān)鍵字的值(總是正數(shù)),否則返回 -1戳鹅。
寫入數(shù)據(jù) put(key, value) - 如果關(guān)鍵字已經(jīng)存在,則變更其數(shù)據(jù)值;如果關(guān)鍵字不存在磺芭,則插入該組「關(guān)鍵字/值」。當(dāng)緩存容量達(dá)到上限時醉箕,它應(yīng)該在寫入新數(shù)據(jù)之前刪除最久未使用的數(shù)據(jù)值钾腺,從而為新的數(shù)據(jù)值留出空間。
進(jìn)階:
你是否可以在 O(1) 時間復(fù)雜度內(nèi)完成這兩種操作讥裤?
示例 :
LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 該操作會使得關(guān)鍵字 2 作廢
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 該操作會使得關(guān)鍵字 1 作廢
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
思路:
采用雙鏈表和哈希表結(jié)合的方式
哈希表查找時間為 O(1)
get函數(shù)實(shí)現(xiàn)思路: key不存在直接返回 -1; 否則將 key對應(yīng)的 value移動到雙鏈表開頭
put函數(shù)實(shí)現(xiàn)思路: key已經(jīng)存在, 將舊節(jié)點(diǎn)刪除, 放入新節(jié)點(diǎn); 若 cache已經(jīng)滿了, 刪除雙鏈表結(jié)尾, 刪除 map中對應(yīng)的 key, 將新節(jié)點(diǎn)插入到 cache, 對應(yīng)的 key插入到 map
時間復(fù)雜度O(1), 空間復(fù)雜度O(n)
代碼:
C++:
class LRUCache
{
private:
list<pair<int, int>> l;
unordered_map<int, list<pair<int, int>>::iterator> m;
int cap;
public:
LRUCache (int capacity)
{
cap = capacity;
}
int get(int key)
{
if (m.find(key) != m.end())
{
int result = (*m[key]).second;
l.erase(m[key]);
l.push_front(make_pair(key, result));
m[key] = l.begin();
return result;
}
return -1;
}
void put(int key, int value)
{
if (m.find(key) != m.end())
{
l.erase(m[key]);
l.push_front(make_pair(key, value));
m[key] = l.begin();
}
else
{
if (l.size() == cap)
{
m.erase(l.back().first);
l.pop_back();
}
l.push_front(make_pair(key, value));
m[key] = l.begin();
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
Java:
class LRUCache extends LinkedHashMap<Integer, Integer>{
private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75F, true);
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
Python:
class LRUCache(dict):
def __init__(self, capacity: int):
self.c = capacity
def get(self, key: int) -> int:
if key in self:
self[key] = self.pop(key)
return self[key]
return -1
def put(self, key: int, value: int) -> None:
key in self and self.pop(key)
self[key] = value
len(self) > self.c and self.pop(next(iter(self)))
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)