leetcode 146.LRU Cache

HashMap + 双向链表,用LinkedList替代过head、tail, 直接超时。

class LRUCache {
    Node head;
    Node tail;
    int size;
    int capacity;

    HashMap map = null;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        map = new HashMap(capacity);
    }

    public int get(int key) {
        if(size == 0) return -1;

        Node node = map.get(key);
        if(node == null) {
            return -1;
        }
        transferNodeLast(node);
        return node.value;
    }

    public void put(int key, int value) {
        Node node = map.get(key);
        if(node != null) {
            node.value = value;
            transferNodeLast(node);
        }
        else {
            Node newNode = new Node(key, value);
            map.put(key, newNode);
            linkNodeLast(newNode);
            size++;
        }
        if(size > capacity) {
            Node first = head;
            head = head.next;
            if(head != null) {
                head.prev = null;
            }
            map.remove(first.key);
            size--;
        }
    }

    private void linkNodeLast(Node node) {
        Node last = tail;
        tail = node;
        if(head == null)
            head = tail;
        else {
            last.next = node;
            node.prev = last;
        }
    }



    private void transferNodeLast(Node node) {
        if(node != tail) {
            Node last = tail;
            Node next = node.next;
            if(node != head) {
                Node prev = node.prev;
                prev.next = next;
                next.prev = prev;
            } else {
                head = next;
                head.prev = null;
            }
            last.next = node;
            node.prev = last;
            node.next = null;
            tail = node;
        }
    }

    class Node {
        int key;
        int value;
        Node next;
        Node prev;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

}
image.png

你可能感兴趣的:(leetcode 146.LRU Cache)