LeetCode 146. LRU 缓存机制

1、题目

image.png

2、分析

使用双向链表来存储缓存节点。方便按照使用顺序来排序。
使用hashmap来存key和缓存节点,方便快速检索。

3、代码

class LRUCache {
    class CacheNode {
        public int key;
        public int value;
        public CacheNode prev;
        public CacheNode next;
        public CacheNode(int k, int v){
            this.key = k;
            this.value = v;
        }
    }
    private CacheNode head, tail;
    private int cap;
    private HashMap map = new HashMap<>();
    public LRUCache(int capacity) {
        cap = capacity;
        head = new CacheNode(0, 0);
        tail = new CacheNode(0, 0);
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if(!map.containsKey(key)){
            return -1;
        }
        CacheNode node = map.get(key);
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
        if(!map.containsKey(key)){
            if(cap == map.size()){
                removeLast();
            }
            CacheNode node = new CacheNode(key, value);
            addToHead(node);
            map.put(key, node);
        }else{
            CacheNode node = map.get(key);
            node.value = value;
            moveToHead(node);
        }
        return;
    }


//后面的这三个方法是抽象出来的。方便重复调用
    public void addToHead(CacheNode node){
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }

    public void moveToHead(CacheNode node){
        node.prev.next = node.next;
        node.next.prev = node.prev;

        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }

    public void removeLast(){
        map.remove(tail.prev.key);
        tail.prev = tail.prev.prev;
        tail.prev.next = tail;
    }
}

/**
 * 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);
 */

你可能感兴趣的:(LeetCode 146. LRU 缓存机制)