146. LRU Cache

Design and implement a data structure forLeast Recently Used (LRU) cache. It should support the following operations:getandput.

get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Follow up:
Could you do both operations inO(1)time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
class LRUCache {

    private class DoubleNode{
        DoubleNode prev;
        DoubleNode next;
        int key;
        int val;

        public DoubleNode(int key, int val, DoubleNode prev, DoubleNode next){
            this.key = key;
            this.val = val;
            this.prev = prev;
            this.next = next;
        }

        public DoubleNode(int key, int val){
            this.key =  key;
            this.val = val;
            this.prev = null;
            this.next = null;
        }
    }

    DoubleNode head = new DoubleNode(-1, -1);
    DoubleNode tail = new DoubleNode(-1, -1);
    int capacity;
    Map<Integer, DoubleNode> hash;

    public LRUCache(int capacity) {
        this.head.next = tail;
        this.tail.prev = head;
        this.capacity = capacity;
        hash = new HashMap<>();
    }

    public int get(int key) {
        if (hash.get(key) == null) return -1;

        DoubleNode node = hash.get(key);
        int ans = node.val;
        node.prev.next = node.next;    
        node.next.prev = node.prev; 
        moveToTail(node);

        return ans;
    }

    public void put(int key, int value) {
        int attempt = get(key);
        if (attempt != -1){
            hash.get(key).val = value;
            return;
        }

        // if already reached capacity
        // remove the top one
        if (hash.size() == this.capacity){
            DoubleNode dump = head.next;
            head.next = dump.next;
            dump.next.prev = head;
            hash.remove(dump.key);
        }

        // create new node, and add into list and map
        DoubleNode newNode = new DoubleNode(key, value);
        moveToTail(newNode);
        hash.put(key, newNode);
    }

    private void moveToTail(DoubleNode node){

        node.prev = tail.prev;
        node.next = tail;
        tail.prev.next = node;
        tail.prev = node;
    }
}

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

results for ""

    No results matching ""