试题
設計と最小のためのデータ構造を実装して使用頻度(LRU)キャッシュ。これは、次の操作をサポートする必要があります。getおよびput。
取得(キー) -返すそうでない場合、キーがキャッシュに存在する場合は、キーの値を(常に正となります)を取得-1。
(キー、値)入れ-セットやキーが既に存在していない場合は、値を挿入します。キャッシュがその容量に達したとき、それは新しい項目を挿入する前に、最低使用項目を無効にする必要があります。
キャッシュは正の容量で初期化されます。
フォローアップ:
あなたはO(1)時間複雑に両方の操作を行うことができますか?
例:
LRUCacheキャッシュ=新しい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
コード
最も簡単には戻って取得またはハッシュに再挿入に価値を置くことです。
class LRUCache {
int capacity;
LinkedHashMap<Integer, Integer> hash;
public LRUCache(int capacity) {
this.capacity = capacity;
this.hash = new LinkedHashMap<>();
}
public int get(int key) {
Integer val = hash.get(key);
if(val == null){
return -1;
}
hash.remove(key);
hash.put(key, val);
return val;
}
public void put(int key, int value) {
hash.remove(key);
hash.put(key, value);
if(hash.size() > capacity){
hash.remove(hash.keySet().iterator().next());
}
}
}
/**
* 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);
*/
public class LRUCache {
Map<Integer, Integer> map;
public LRUCache(int capacity) {
this.map = new LinkedHashMap<Integer, Integer>(128, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};
}
public int get(int key) {
return map.getOrDefault(key, -1);
}
public void put(int key, int value) {
map.put(key, value);
}
}