算法之LRU模版1

package com.zhang.reflection.面试.算法模版.LRU;
import java.util.HashMap;
import java.util.Map;

public class LRU {
    class Node<K,V>{
        K key;
        V value;
        Node pre;
        Node next;
        public Node(){
            this.pre=null;
            this.next=null;
        }
        public Node(K key,V value){
            this.key=key;
            this.value=value;
            this.pre=null;
            this.next=null;
        }
    }
    class DoubleLinkedList{
        Node head;
        Node tail;
        public DoubleLinkedList(){
            head=new Node();
            tail=new Node();
            head.next=tail;
            tail.pre=head;
        }
        public void addHead(Node node){
            node.next=head.next;
            node.pre=head;
            head.next.pre=node;
            head.next=node;
        }
        public void removeTail(Node node){
            node.pre.next=node.next;
            node.next.pre=node.pre;
            node.pre=null;
            node.next=null;
        }
        public Node getLast(){
            return tail.pre;
        }
    }
    int cacheSize;
    Map<Integer,Node<Integer,Integer>> map;
    DoubleLinkedList list;
    public LRU(int cacheSize){
        this.cacheSize=cacheSize;
        map=new HashMap<Integer,Node<Integer,Integer>>();
        list=new DoubleLinkedList();
    }
    public int get(int key){
        if(!map.containsKey(key)){
            return -1;
        }
        Node<Integer,Integer> node=map.get(key);
        list.removeTail(node);
        list.addHead(node);
        return node.value;
    }
    public void put(int key,int value){
        if(map.containsKey(key)){
            Node<Integer,Integer> node=map.get(key);
            node.value=value;
            list.removeTail(node);
            list.addHead(node);
        }else{
            if(cacheSize==map.size()){
                Node<Integer,Integer> last = list.getLast();
                map.remove(last.key);
                list.removeTail(last);
            }
            Node<Integer,Integer> node=new Node<>(key,value);
            map.put(key,node);
            list.addHead(node);
        }
    }
    public static void main(String[] args) {
        LRU t=new LRU(3);
        t.put(1,1);
        t.put(2,2);
        t.put(3,3);
        System.out.println(t.map.keySet());
        t.get(1);
        t.put(4,4);
        System.out.println(t.map.keySet());
        t.put(5,5);
        System.out.println(t.map.keySet());
    }
}

全部评论

相关推荐

07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务