二刷146. LRU Cache

Hard FB tag
HashMap + LinkedList. 思路还挺特别的,记录的是prevNodes的map, 可以留意一下如何写moveToTail这个helper method的写法

class LRUCache {
    class Node{
        Node next;
        int key;
        int val;
        public Node(int key, int val){
            this.key = key;
            this.val = val;
            this.next = null;
        }
    }
    private int initialCapacity;
    private int size;
    private Node head;
    private Node tail;
    private Map<Integer, Node> prevNodes;
    public LRUCache(int capacity) {
        this.initialCapacity = capacity;
        this.size = 0;
        this.head = new Node(0,0);
        this.tail = head;
        this.prevNodes = new HashMap<>(capacity);
    }

    public int get(int key) {
        if (!prevNodes.containsKey(key)){
            return -1;
        }    
        Node prev = prevNodes.get(key);
        Node curt = prev.next;
        if (curt != tail){
            moveToTail(curt);
        }
        return curt.val;
        //move this most recently used curt node to the tail
    }
    
    private void moveToTail(Node curt){
        Node prev = prevNodes.get(curt.key);
        prev.next = curt.next;
        prevNodes.put(prev.next.key, prev);
        tail.next = curt;
        prevNodes.put(curt.key, tail);
        tail = curt;
    }
    
    public void put(int key, int value) {
        //get(key) will move this node to the tail, so we don't need to implement it again
        if (get(key) != -1){
            Node prev = prevNodes.get(key);
            prev.next.val = value;
            return;
        }
        Node newNode = new Node(key, value);
        tail.next = newNode;
        prevNodes.put(newNode.key, tail);
        tail = tail.next;
        size++;
        if (size > initialCapacity){
            prevNodes.remove(head.next.key);
            head.next = head.next.next;
            if (head.next != null){
                prevNodes.put(head.next.key, head);
            }
            size--;
        } 
    }
}

/**
 * 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);
 */
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/f20e939f3365
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞