L146 LRU Cache

HashMap + double LinkedList

Problem

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

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.

The cache is initialized with a positive capacity.

Solution

HashMap + double LinkedList TC: O1 for both put and get function SC: O(capacity)

HashMap is for keeping track of the keys, and keep its values in double linked list.

Class LRUCach{
    Map<Integer, ListNode> map;
    ListNode head;
    ListNode tail;
    int size;
    int capacity;
    
    public LRUCache(int capacity){
        map = new HashMap<>;
        head = new ListNode(0,0);
        tail = new ListNOde(0,0);
        head.next = tail;
        tail.prev = head;
        size = 0;
        this.capacity = capacity;
    }
    
    publc int get(int key){
        if(!map.contaisKey(key)) return -1;
        ListNode node= map.get(key);
        delete(node);
        addToTail(node);
        return node.value;
    }
    public put(int key, int value){
        if(!map.containsKey(key)){
            ListNode = newNode = new ListNode(key, value);
            if(size == capacity){
                ListNode deleteNode = head.next;
                delete(deletNode);
                map.remove(deleteNode,key);
                size --;
            }
            addToTail(newNode);
            map.put(key, newNode);
            size ++;
            return;
        }
        ListNode curNode = map.get(key);
        curNode.val = value;
        delete(curNode);
        addToTail(curNode);
        return;
    }
    private void delete(ListNode node){
        node.prev.next = node.next;
        node.next.prev = node.prev;
        node.next = null;
        node.prev = null;
    }
    private void addToTail(ListNode node){
        node.next = tial;
        node.prev = tail.prev;
        tail.prev.next = node;
        tail.prev = node;
    }
    class ListNode{
        int key;
        int value;
        ListNode prev;
        ListNode next;
        public ListNode(int key, int value){
            this.key = key;
            this.value = value;
            prev = null;
            next = null;
        }
    }
}

Last updated

Was this helpful?