//運用你所掌握的數據結構,設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數據 get 和 寫入數據 put 。
//
// 獲取數據 get(key) - 如果關鍵字 (key) 存在於緩存中,則獲取關鍵字的值(總是正數),否則返回 -1。
//寫入數據 put(key, value) - 如果關鍵字已經存在,則變更其數據值;如果關鍵字不存在,則插入該組「關鍵字/值」。當緩存容量達到上限時,它應該在
//寫入新數據之前刪除最久未使用的數據值,從而爲新的數據值留出空間。
//
//
//
// 進階:
//
// 你是否可以在 O(1) 時間複雜度內完成這兩種操作?
//
//
//
// 示例:
//
// LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );
//
//cache.put(1, 1);
//cache.put(2, 2);
//cache.get(1); // 返回 1
//cache.put(3, 3); // 該操作會使得關鍵字 2 作廢
//cache.get(2); // 返回 -1 (未找到)
//cache.put(4, 4); // 該操作會使得關鍵字 1 作廢
//cache.get(1); // 返回 -1 (未找到)
//cache.get(3); // 返回 3
//cache.get(4); // 返回 4
//
// Related Topics 設計
import java.util.HashMap;
import java.util.Map;
//leetcode submit region begin(Prohibit modification and deletion)
class LRUCache {
//定義一個類
class Node{
int key;
int value;
Node pre;
Node next;
public Node(int key,int value){
this.key=key;
this.value=value;
}
}
//定義基本信息
Node head;
Node tail;
Map<Integer,Node> map;
//當前大小
int size=0;
//容量
int capacity;
public LRUCache(int capacity) {
head=new Node(0,0);
tail=new Node(0,0);
head.next=tail;
tail.pre=head;
map=new HashMap<>();
size=0;
this.capacity=capacity;
}
//取值操作
//1:有值,刪除老key,更新新key
//2:無值:返回-1
public int get(int key) {
if(map.containsKey(key)){
Node node=map.get(key);
remove(key);
addHead(key,node.value);
return node.value;
}
else{
return -1;
}
}
//存值操作
//1:不存在 :直接隊首
//2:存在:刪除key,對應值更新到隊首
public void put(int key, int value) {
if(map.containsKey(key)){
remove(key);
addHead(key,value);
}else{
addHead(key,value);
}
}
//根據key刪除對應的節點
private void remove(int key){
Node node=map.get(key);
Node next=node.next;
Node pre=node.pre;
pre.next=next;
next.pre=pre;
map.remove(key);
size--;
}
//在head後加一個node
private void addHead(int key,int value){
Node node=new Node(key,value);
Node next=head.next;
head.next=node;
node.next=next;
next.pre=node;
node.pre=head;
size++;
map.put(key,node);
if(size>capacity){
Node preTail=tail.pre;
remove(preTail.key);
}
}
}
/**
* 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);
*/
//leetcode submit region end(Prohibit modification and deletion)