-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
77 lines (65 loc) · 1.08 KB
/
LRUCache.cpp
File metadata and controls
77 lines (65 loc) · 1.08 KB
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
76
class LRUCache
{
public:
std::vector<std::pair<int, int>> cache;
int cap;
LRUCache(int capacity)
{
cap = capacity;
}
int get(int key)
{
auto itr = cache.begin();
for (int i = 0; i<cache.size();i++)
{
if (cache[i].first == key)
{
int tmp = cache[i].second;
cache.erase(itr);
cache.push_back({ key,tmp });
return tmp;
}
itr++;
}
return -1;
}
std::vector<std::pair<int, int>>::iterator find(int key)
{
auto cacheItr = cache.begin();
for (auto it : cache)
{
if (it.first == key)
return cacheItr;
cacheItr++;
}
return cache.end();
}
void put(int key, int value)
{
auto it = find(key);
if (it == cache.end())
{
if (cache.size() == cap)
{
cache.erase(cache.begin());
}
}
else
{
cache.erase(it);
}
cache.push_back({ key,value });
}
};
int main()
{
LRUCache cache(2);
std::cout << cache.get(2) << std::endl;
cache.put(2, 6);
std::cout<<cache.get(1)<<std::endl;
cache.put(1, 5);
cache.put(1, 2);
std::cout << cache.get(1) << std::endl;
std::cout << cache.get(2) << std::endl;
return 0;
}