# 146. LRU Cache

&#x20;**146. LRU Cache**

Design and implement a data structure for [Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU). 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
```

***My Solutions:***&#x20;

* 要求get和put都是O(1)的时间复杂度， 那么必须要用一个hashmap
* 光用hashmap无法支持least recently used。如果想要知道某个元素使用的时间顺序，需要有一个list， 每次使用(get/put)的时候把这个元素放到list的最前面。 如果容量到了需要剔除的时候，直接把list的最后一个元素删除
* 如何保证把list里面的某个元素换到最前面的时候也是O(1)操作呢？&#x20;
  * 用arraylist肯定不可以， 因为把某一个元素放到最前面以后，还需要把后面的元素全部移动一遍，复杂度最差可能是O(N)
  * 用linkedlist是否可以？ linkedlist删除中间的元素时候，有没有办法直接把前后的元素连起来就可以了？ 这里想到如果每个node有prev,next, 那就可以这样操作了。所以其实这里只要实现一个doubly linked list, 然后在加上前面的那个map， 每次来一个key的时候，可以直接定位到这个node， 然后每个node有prev和next，那就可以用O(1)的时间移动位置，然后就可以完成get和put操作

有几个地方需要注意：

* 在get一个node之后，需要把node从现在的位置删去，然后放在最前面。
* 在put的时候检查需要是不是已经存在了有同样key的node。
  * 如果已经有了同样key的node，更新ta的value。同样的把node从现在的位置删去，然后放在最前面。
  * 如果没有同样key的node，检查capacity，满的话需要删掉最后一个node。然后创建新的node加到最前面。

```java
class LRUCache {
    
    class Node {
        int key, value;
        Node pre, next;
        public Node (int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    
    // 这两个是dummy，本身不储存真正的node值，只是指向linked list的头和尾
    Node head, tail; 
    int capacity;
    Map<Integer, Node> map;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.map = new HashMap<>();
        head = new Node(-1, -1);
        tail = new Node(-1, -1);
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if (capacity == 0) return -1;
        
        Node node = map.get(key);
        if (node == null) return -1;
        
        unlink(node);
        insertToHead(node);
        return node.value;
    }
    
    private void unlink(Node node) {
        Node prev = node.prev, next = node.next;
        prev.next = next;
        next.prev = prev;
    }
    
    private void insertToHead(Node node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }
    
    public void put(int key, int value) {
        if (capacity == 0) return; // 如果map的capacity是零，无法加入任何node
        
        Node node = map.get(key);
        if (null == node) { // 没有对应key的node，加入新node
    
            if (map.size() == capacity) { // map已经满了，先删除最后一个
                Node lastNode = tail.prev;
                map.remove(lastNode.key);    
                unlink(lastNode);
            }
            
            node = new Node(key, value);
            map.put(key, node);
            insertToHead(node);
 
        } else {
            node.value = value;
            unlink(node); // 把现在的node从linked list中删去
            insertToHead(node); // 因为这个node要插到linked list最前面
        }
    }
}

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