# 146. LRU Cache (Hard)

https://leetcode.com/problems/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.

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.put(4, 4);    // evicts key 1
cache.get(3);       // returns 3
cache.get(4);       // returns 4
```

## Solutions

### 1.

``````class LRUCache {

int capacity = 0;
int version = 0;

Map<Integer, Integer> versionMap = new HashMap<>();
Map<Integer, Integer> lruCache = new HashMap<>();
Queue<Integer> versionQueue = new PriorityQueue<>(Comparator.comparingInt(o -> versionMap.get(o.intValue())));

public LRUCache(int capacity) {
this.capacity = capacity;
}

public int get(int key) {
if (!lruCache.containsKey(key)) {
return -1;
}

updateVersion(key);

return lruCache.get(key);
}

public void put(int key, int value) {
if (lruCache.containsKey(key)) {
lruCache.put(key, value);

updateVersion(key);

return;
}

// if exceeds the capacity of queue, remove least recent used element at first
if (versionMap.size() >= capacity) {
removeLRU();
}

version++;

lruCache.put(key, value);
versionMap.put(key, version);
}

private void updateVersion(Integer key) {
version++;

// update version
versionMap.put(key, version);

// resort version queue
versionQueue.remove(key);
}

private void removeLRU() {
int k = versionQueue.poll();

lruCache.remove(k);
versionMap.remove(k);
versionQueue.remove(k);
}
}
``````