Leetcode 146. LRU Cache

来源:互联网 发布:淘宝cosplay服装店 编辑:程序博客网 时间:2024/05/10 16:03
public class LRUCache {    // double linked list    private class Node {        Node prev;        Node next;        int key;        int value;                public Node (int key, int value) {            this.key = key;            this.value = value;            this.prev = null;            this.next = null;        }    }        private int capacity;    private HashMap<Integer, Node> map = new HashMap<Integer, Node>();    private Node head = new Node(-1, -1);    private Node tail = new Node(-1, -1);        public LRUCache(int capacity) {        this.capacity = capacity;        tail.prev = head;        head.next = tail;    }        public int get(int key) {        if (!map.containsKey(key)) {            return -1;        }                // delete current node from the list and move it to tail        Node curr = map.get(key);        curr.prev.next = curr.next;        curr.next.prev = curr.prev;                moveToTail(curr);                return map.get(key).value;    }        public void put(int key, int value) {        if (get(key) != -1) {            map.get(key).value = value;            return;        }                // remove least recently used node        if (map.size() == capacity) {            map.remove(head.next.key);                  head.next = head.next.next;            head.next.prev = head;        }                // insert new node to the tail        Node newNode = new Node(key, value);        map.put(key, newNode);        moveToTail(newNode);    }        public void moveToTail(Node curr) {        curr.prev = tail.prev;        tail.prev = curr;        curr.prev.next = curr;        curr.next = tail;    }}
0 0