LRU Cache

来源:互联网 发布:新网域名证书生成 编辑:程序博客网 时间:2024/04/30 04:44

Q:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.


Solution:

Both set and get are counted as a operation, use a doubly linked list to track the head and the tail. The get and set have O(1) time.

class DoublyLinkedListNode {        DoublyLinkedListNode prev;        DoublyLinkedListNode next;        int key;        int val;                public DoublyLinkedListNode(int key, int val) {            this.key = key;            this.val = val;            prev = null;            next = null;        }}    public class LRUCache {    HashMap<Integer, DoublyLinkedListNode> cache = new HashMap<Integer, DoublyLinkedListNode>();    // head.prev points to the tail of the list, so that we can get the tail in O(1) time.    DoublyLinkedListNode head = null;    private int capacity;        private void removeNode(DoublyLinkedListNode node) {        if (node == head)            head = node.next;        node.prev.next = node.next;        node.next.prev = node.prev;    }        private void addHead(DoublyLinkedListNode node) {                if (head == null) {            head = node;            head.prev = head;            head.next = head;        }        else {            node.next = head;            node.prev = head.prev;            head.prev.next = node;            head.prev = node;            head = node;        }    }        public LRUCache(int capacity) {        this.capacity = capacity;    }        public int get(int key) {        if (!cache.containsKey(key))            return -1;        DoublyLinkedListNode node = cache.get(key);        removeNode(node);        addHead(node);        return node.val;    }        public void set(int key, int value) {        if (cache.containsKey(key)) {            DoublyLinkedListNode node = cache.get(key);            node.val = value;            cache.put(key, node);            removeNode(node);            addHead(node);        }        else {            if (cache.size() < capacity) {                DoublyLinkedListNode node = new DoublyLinkedListNode(key, value);                cache.put(key, node);                addHead(node);            }            else {                DoublyLinkedListNode tail = head.prev;                removeNode(tail);                cache.remove(tail.key);                DoublyLinkedListNode newHead = new DoublyLinkedListNode(key, value);                cache.put(key, newHead);                addHead(newHead);            }        }    }}


0 0
原创粉丝点击