[LeetCode] LRU Cache

146. LRU Cache

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.

Follow up:
Could you do get and put in O(1) time complexity?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class LRUCache {
private:
unordered_map<int, list<pair<int,int>>::iterator> m;
list<pair<int, int>> l;
int c;

void moveFront(list<pair<int, int>>& li, list<pair<int,int>>::iterator it) {
if(it != begin(li)) {
li.splice(li.begin(), li, it, next(it));
}
}

void insert(int key, int value) {
l.push_front({key, value});
m[key] = l.begin();
if(l.size() > c) {
balance(l.back().first);
}
}

void balance(int key) {
m.erase(key);
l.pop_back();
}
public:
LRUCache(int capacity) : c(capacity) {}

int get(int key) {
if(!m.count(key)) return -1;
int res = m[key]->second;
moveFront(l, m[key]);

return res;
}

void put(int key, int value) {
if(!m.count(key)) {
insert(key, value);
} else {
m[key]->second = value;
moveFront(l, m[key]);
}
}
};

/**
* 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);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/22/PS/LeetCode/lru-cache/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.