-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.cpp
75 lines (64 loc) · 1.6 KB
/
lru.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// lru.cpp
// xcode
//
// Created by Gokul Nadathur on 8/26/16.
// Copyright © 2016 Gokul Nadathur. All rights reserved.
//
#include <unordered_map>
#include <list>
using namespace std;
class LRUCache{
public:
struct Element {
int k,v;
Element() {
k = v = -1;
}
};
int _capacity;
list<Element*> _lru;
unordered_map<int, list<Element*>::iterator> _cache;
LRUCache(int capacity) {
Element *p = new Element[capacity];
for (auto i = 0; i < capacity; ++i) {
_lru.push_back(p);
p++;
}
}
int get(int key) {
auto it = _cache.find(key);
if (it == _cache.end()) {
return -1;
}
auto lit = it->second;
auto val = (*lit)->v;
updateLRU(it);
return val;
}
void set(int key, int value) {
auto it = _cache.find(key);
if (it != _cache.end()) {
auto lit = it->second;
(*lit)->v = value;
updateLRU(it);
return;
}
auto ptr = _lru.front();
_lru.pop_front();
if (ptr->k != -1) {
_cache.erase(ptr->k);
}
ptr->k = key; ptr->v = value;
_lru.push_back(ptr);
_cache[key] = std::prev(_lru.end());
}
void updateLRU(unordered_map<int, list<Element*>::iterator>::iterator& it) {
auto k = it->first;
auto lit = it->second;
auto ptr = *lit;
_lru.erase(lit);
_lru.push_back(ptr);
_cache[k] = std::prev(_lru.end());
}
};