-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.cpp
More file actions
75 lines (66 loc) · 1.77 KB
/
146.cpp
File metadata and controls
75 lines (66 loc) · 1.77 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
//
// 146.cpp
// LeetCode
//
// Created by 张佐玮 on 15/9/1.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: LRU Cache
//
#include <iostream>
#include <unordered_map>
#include <list>
using namespace std;
class LRUCache{
public:
struct CacheUnit {
int key;
int val;
CacheUnit(int k, int v): key(k), val(v) {}
};
LRUCache(int capacity): size(capacity), currentSize(0) {
}
int get(int key) {
auto cacheHashIt = cacheHash.find(key);
if (cacheHashIt == cacheHash.end()) {
return -1;
}
cache.splice(cache.begin(), cache, cacheHashIt -> second);
return cache.front() -> val;
}
void set(int key, int value) {
auto cacheHashIt = cacheHash.find(key);
if (cacheHashIt == cacheHash.end()) {
if (currentSize >= size) {
cacheHash.erase(cache.back() -> key);
delete cache.back();
cache.pop_back();
}
else {
currentSize++;
}
cache.push_front(new CacheUnit(key, value));
cacheHash[key] = cache.begin();
}
else {
(*(cacheHashIt -> second)) -> val = value;
cache.splice(cache.begin(), cache, cacheHashIt -> second);
}
}
private:
unordered_map<int, list<CacheUnit*>::iterator> cacheHash;
list<CacheUnit*> cache;
int size, currentSize;
};
class Test {
public:
void sample() {
//1,[set(2,1),get(2),set(3,2),get(2),get(3)]
LRUCache lruCache(1);
lruCache.set(2,1);
cout << lruCache.get(2) << endl;
lruCache.set(3,2);
cout << lruCache.get(2) << endl;
cout << lruCache.get(3) << endl;
}
};