概述
class LRUCache {
int capacity;
int len=0;
private Map<Integer,DoubleNode> map=new HashMap<Integer,DoubleNode>();
DoubleNode head;
DoubleNode tail;
public LRUCache(int capacity) {
this.capacity=capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
DoubleNode latest = map.get(key);
removeNode(latest);
setHead(latest);
return latest.val;
} else {
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key)){
DoubleNode doubleNode=map.get(key);
doubleNode.val=value;
removeNode(doubleNode);
setHead(doubleNode);
}else{
DoubleNode doubleNode=new DoubleNode(key,value);
if(len<capacity){
map.put(key,doubleNode);
setHead(doubleNode);
len++;
}else{
map.remove(tail.key);
//removeNode(tail);
tail = tail.pre;
if (tail != null) {
tail.next = null;
}
setHead(doubleNode);
map.put(key,doubleNode);
}
}
}
public void setHead(DoubleNode node){
node.next=head;
node.pre=null;
if(head!=null){
head.pre=node;
}
head=node;
if(tail==null){
tail=node;
}
}
public void removeNode(DoubleNode node){
DoubleNode pre=node.pre;
DoubleNode post=node.next;
DoubleNode curr=node;
if(pre!=null){
pre.next=post;
}else{
head=post;
}
if(post!=null){
post.pre=pre;
}else{
tail=pre;
}
curr.next=null;
curr.pre=null;
}
}
class DoubleNode{
int key;
int val;
DoubleNode pre;
DoubleNode next;
public DoubleNode(int key,int val){
this.key=key;
this.val=val;
}
}
/**
* 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);
*/
最后
以上就是老实糖豆为你收集整理的leetcode146 LRUCache的全部内容,希望文章能够帮你解决leetcode146 LRUCache所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复