- 時隔多日,終於是手癢來寫一道,正好在複習操作系統,所以就刷了這個與之相關的,Leetcode真的啥都有~
題目
運用你所掌握的數據結構,設計和實現一個 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);
cache.put(3, 3);
cache.get(2);
cache.put(4, 4);
cache.get(1);
cache.get(3);
cache.get(4);
方案:數組解法
class LRUCache {
private int[][] cache;
private int row;
public LRUCache(int capacity) {
cache = new int[capacity][3];
for (int i = 0; i < capacity; i++) {
cache[i][0] = -1;
}
row = capacity;
}
public int get(int key) {
int res = -1;
for (int i = 0; i < this.row; i++) {
if (cache[i][0] == key) {
cache[i][1] = 0;
res = cache[i][2];
} else if (cache[i][0] == -1) {
break;
} else {
cache[i][1]++;
}
}
return res;
}
public void put(int key, int value) {
int max = -1;
int index = -1;
boolean find = false;
for (int i = 0; i < this.row; i++) {
if (cache[i][0] == key) {
cache[i][1] = 0;
cache[i][2] = value;
index = -1;
find = true;
} else if (cache[i][0] == -1&&!find) {
cache[i][0] = key;
cache[i][1] = 0;
cache[i][2] = value;
return;
} else {
cache[i][1]++;
if (max < cache[i][1]&&!find) {
max = cache[i][1];
index = i;
}
}
}
if (index != -1) {
cache[index][0] = key;
cache[index][1] = 0;
cache[index][2] = value;
}
}
}
複雜度計算
方案:LinkedHashMap
- 突然發現LinkedHashMap的可以實現LRU,看源碼註釋:重寫下removeEldestEntry,這就直接實現了~,算作弊吧這,哈哈,正常來講應該是自己寫個HashMap之類的搞一搞
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;
}
}
複雜度計算