public class LRUCache146_2 {
private Map<Integer, int[]> cache = null;
private int capacity = 0;
public LRUCache146_2(int capacity) {
cache = new LinkedHashMap<>();
this.capacity = capacity;
}
/**
* 获取key的值
*
* @param key key
* @return value
*/
public int get(int key) {
if (cache.containsKey(key)) {
int[] ints = cache.get(key);
cache.remove(key);
cache.put(key, ints);
return ints[1];
}
return -1;
}
/**
* 向LRU中插入值
*
* @param key key
* @param value value
*/
public void put(int key, int value) {
int[] arr = new int[]{key, value};
//如果存在这个key就更新value
if (cache.containsKey(key)) {
cache.remove(key);
cache.put(key, arr);
return;
}
if (cache.size() < capacity) {
cache.put(key, arr);
} else if (cache.size() == capacity) {
int deleteKey = cache.entrySet().iterator().next().getKey();
cache.remove(deleteKey);
cache.put(key, arr);
}
}
}
时间复杂度:O(1)
时间复杂度:O(n)