一、題目描述
運用你所掌握的數據結構,設計和實現一個 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
二、解題思路
用兩個數據結構,兩者結合起來便可以實現效果。直接看代碼即可。
1、用於存儲最近使用次數的(我這裏用了棧,也可以用其他數據結構)
2、用於存儲數據的,便於獲取get和存入get(這裏我用了hashmap)
三、可運行java代碼
class LRUCache {
Stack<Integer> stack;
Map<Integer, Integer> map;
int size;
public LRUCache(int capacity) {
stack = new Stack<>();
map = new HashMap<>();
size = capacity;
}
public int get(int key) {
if(!stack.contains(key)){
return -1;
}
stack.remove(Integer.valueOf(key));
stack.push(key);
return map.get(key);
}
public void put(int key, int value) {
if(stack.contains(key)){
stack.remove(Integer.valueOf(key));
}else{
if(stack.size() == size){
int count = stack.remove(0);
map.remove(count);
}
}
stack.push(key);
map.put(key, value);
}
}
/**
* 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);
*/