package Interview;
import java.util.HashMap;
import java.util.Map;
/*
* 实现最近最少使用算法,且get,put时间复杂度为O(1)
* */
public class LRUCache {
private Map<Integer, DLinkedList> cache;
DLinkedList tail=null;
DLinkedList head=null;
int capacity;
public LRUCache(int capacity) {
// TODO Auto-generated constructor stub
cache=new HashMap<>();
this.capacity=capacity;
}
public int get(int key){
if (cache.containsKey(key)) {
DLinkedList target=cache.get(key);
int value=target.value;
target.update();
return value;
}else {
return -1;
}
}
public void set(int key,int value){
if(cache.containsKey(key)){
DLinkedList target=cache.get(key);
target.value=value;
target.update();
}else {
if(capacity==0) return;
if(cache.size()==capacity){
cache.remove(head.key);
head.removeFromHead();
}
DLinkedList newNode=new DLinkedList(key, value);
LinkedList+HashMap实现LRU算法
最新推荐文章于 2021-01-31 23:54:02 发布