注意一下几项
1. 借助linklist动态储存key的使用情况,将每次使用的key对应的节点变化到链表尾部,0位置为最少使用的key
2. 题目对时间复杂度有要求,linklist获得某个key,需要用O(1)的map查找,而是O(n)的循环查找
3. 根据以上两个条件,需要实现map+linklist的数据结构,linklist存储键值和最少用到的key,map根据key找到list对应的节点
public class LRUCache {
private Map<Integer, Node> map;
private Integer capacity;
private Node head;
private Node tail;
private class Node {
public Integer key;
public Node parent;
public Node next;
public Integer value;
private Node(Integer key, Node parent, Node next, Integer value) {
this.key = key;
this.parent = parent;
this.next = next;
this.value = value;
}
}
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<Integer, Node>(capacity, 1);
head = new Node(null, null, null, null);
tail = head;
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
if(map.size() == 1){
return node.value;
}
node.parent.next = node.next;
if(node.next !=null){
node.next.parent = node.parent;
}else {
tail = node.parent;
}
tail.next = node;
node.parent = tail;
tail = node;
tail.next=null;
return node.value;
}
public void set(int key, int value) {
Node toDelNode = null;
if (map.containsKey(key)) {
toDelNode = map.get(key);
} else if (map.size() == capacity) {
toDelNode = head.next;
}
if(toDelNode != null){
toDelNode.parent.next = toDelNode.next;
if(toDelNode.next != null){
toDelNode.next.parent = toDelNode.parent;
}else{
tail = toDelNode.parent;
}
map.remove(toDelNode.key);
if(map.isEmpty()){
tail = head;
}
}
if(map.size() < capacity){
Node node = new Node(key, tail, null, value);
tail.next = node;
tail = node;
tail.next=null;
map.put(key, node);
}
}
}