本文共 1192 字,大约阅读时间需要 3 分钟。
LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
public class LRUCache { private java.util.LinkedHashMapstorage = new java.util.LinkedHashMap<>(); private int capacity; public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { Integer value = storage.get(key); if(value == null){ return -1; } storage.remove(key); storage.put(key, value); return value; } public void set(int key, int value) { Integer val = storage.get(key); if (val == null && storage.size() == capacity) { storage.remove(storage.keySet().iterator().next()); } else if (val != null) { storage.remove(key); } storage.put(key, value); }}
转载地址:http://kvuni.baihongyu.com/