?LeetCode刷題實(shí)戰(zhàn)146:LRU 緩存機(jī)制
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
題意
LRUCache(int capacity) 以正整數(shù)作為容量 capacity 初始化 LRU 緩存
int get(int key) 如果關(guān)鍵字 key 存在于緩存中,則返回關(guān)鍵字的值,否則返回 -1 。
void put(int key, int value) 如果關(guān)鍵字已經(jīng)存在,則變更其數(shù)據(jù)值;如果關(guān)鍵字不存在,則插入該組「關(guān)鍵字-值」。當(dāng)緩存容量達(dá)到上限時,它應(yīng)該在寫入新數(shù)據(jù)之前刪除最久未使用的數(shù)據(jù)值,從而為新的數(shù)據(jù)值留出空間。
輸入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
輸出
[null, null, null, 1, null, -1, null, -1, 3, 4]
解釋
LRUCache lRUCache = new?LRUCache(2);
lRUCache.put(1, 1); // 緩存是 {1=1}
lRUCache.put(2, 2); // 緩存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 該操作會使得關(guān)鍵字 2 作廢,緩存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 該操作會使得關(guān)鍵字 1 作廢,緩存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
解題
/**
?* HashMap.Node subclass for normal LinkedHashMap entries.
?*/
static?class?Entryextends?HashMap.Node {
?????Entrybefore, after;
?????Entry(int?hash, K key, V value, Nodenext) {
??????????super(hash, key, value, next);
?????}
}
put和get操作的時間復(fù)雜度均是O(1)。空間復(fù)雜度是O(n),其中n為緩存容量。
class?LRUCache?{
?
????private?int?capacity;
????private?LRULinkedHashMaplruLinkedHashMap = new?LRULinkedHashMap<>();
?
????private?class?LRULinkedHashMap<K, V> extends?LinkedHashMap<K, V> {
????????@Override
????????protected?boolean?removeEldestEntry(Map.Entryeldest) ?{
????????????if?(size() > capacity) {
????????????????return?true;
????????????} else?{
????????????????return?false;
????????????}
????????}
????}
?
????public?LRUCache(int?capacity)?{
????????this.capacity = capacity;
????}
?
????public?int?get(int?key)?{
????????Integer value = lruLinkedHashMap.get(key);
????????if?(null?== value) {
????????????return?-1;
????????}
????????lruLinkedHashMap.remove(key);
????????lruLinkedHashMap.put(key, value);
????????return?value;
????}
?
????public?void?put(int?key, int?value)?{
????????if?(lruLinkedHashMap.containsKey(key)) {
????????????lruLinkedHashMap.remove(key);
????????}
????????lruLinkedHashMap.put(key, value);
????}
?
}
