Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.java
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.this
Follow up:
Could you do both operations in O(1) time complexity?spa
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
設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持如下操做: 獲取數據 get
和 寫入數據 put
。code
獲取數據 get(key) - 若是密鑰 (key) 存在於緩存中,則獲取密鑰的值(老是正數),不然返回 -1。
寫入數據 put(key, value) - 若是密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據以前刪除最近最少使用的數據值,從而爲新的數據值留出空間。blog
按照所給的例子看一下cache內部是如何變化的。ip
front | back | result | |
put(1, 1) | (1, 1) | ||
put(2, 2) | (2, 2) | (1, 1) | |
get(1) | (1, 1) | (2, 2) | 1 |
put(3, 3) | (3, 3) | (1, 1) | |
get(2) | (3, 3) | (1, 1) | -1 |
put(4, 4) | (4, 4) | (3, 3) | |
get(1) | (4, 4) | (3, 3) | -1 |
get(3) | (3, 3) | (4, 4) | 3 |
get(4) | (4, 4) | (3, 3) | 4 |
很清楚的就理解了LRU的機制,當get的key在cache中已經存在時,就將存儲的內容放到最前面,get的key不存在時就返回-1。ci
put的新的key-value時,若是達到了容量上限,就刪除一個最近最少使用的,實際上也是隊尾的元素,而後將新的key-value存儲到最前面。rem
由於咱們每次要O(1)的複雜度,因此能夠使用hashmap來get數據,而當容量達到上限時,要刪除最近最少使用的,且要在最前面put進新的數據,要使用一個雙向鏈表,來保證O(1)的時間複雜度。
java中能夠使用LinkeHashMap來實現LRU緩存。
C++
class LRUCache { public: LRUCache(int capacity) { cap = capacity; } int get(int key) { auto it = map.find(key); if(it == map.end()) return -1; l.splice(l.begin(), l, it->second); return it->second->second; } void put(int key, int value) { auto it = map.find(key); if(it != map.end()){ l.erase(it->second); } l.push_front(make_pair(key, value)); map[key] = l.begin(); if (map.size() > cap) { int k = l.rbegin()->first; l.pop_back(); map.erase(k); } } private: int cap; list<pair<int, int>> l; unordered_map<int, list<pair<int, int>>::iterator> map; };
Java
class LRUCache { public LRUCache(int capacity) { this.capacity = capacity; map = new LinkedHashMap<>(); } public int get(int key) { if(map.containsKey(key)) { int value = map.get(key); map.remove(key); map.put(key, value); return value; } return -1; } public void put(int key, int value) { if(map.containsKey(key)) { map.remove(key); } map.put(key, value); if(map.size() > capacity) { map.remove(map.keySet().iterator().next()); } } private int capacity; private LinkedHashMap<Integer, Integer> map; }