LeetCode146 LRU Cache

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.

Follow up:
Could you do both operations in O(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
思路:使用哈希map和双链表解决。
双链表相对于单链表的特点:节点可以在没有其他引用的情况下删除自身,单链表要删除自身需要知道自己的前缀。

   class LRUCache {
    private int capacity;
    private Node head;
    private Node tail;
    private HashMap<Integer,Node> map;
    
    class Node{
        int key;
        int val;
        Node prev;
        Node next;
        public Node(){
            
        }
        public Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if(!map.containsKey(key)){
            return -1;
        }
        moveToFront(map.get(key));
        return map.get(key).val;
    }
    
    public void put(int key, int value) {
        if(capacity ==0)
            return;
        if(map.containsKey(key)){
            map.get(key).val = value;
            moveToFront(map.get(key));
        } else{
            freeSpace();
            Node n = new Node(key,value);
            map.put(key,n);
            addToFront(n);
        }        
    }
    
    private void freeSpace(){
        if(map.size() == capacity){
            Node toRemove = head.next;
            map.remove(toRemove.key);
            Node next = toRemove.next;
            head.next = next;
            next.prev = head;   
        }
    }
    
    private void moveToFront(Node newNode){
        Node prev = newNode.prev;
        Node next = newNode.next;
        prev.next = next;
        next.prev = prev;
        addToFront(newNode);
    }
    
    private void addToFront(Node newNode){
        Node prev = tail.prev;
        prev.next = newNode;
        newNode.prev = prev;
        newNode.next = tail;
        tail.prev = newNode;
    }
}

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

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85116940
今日推荐