您的位置:首页 > 编程语言

面试手撕代码高频题目:实现一个LRU Cache

2020-07-24 08:40 78 查看

LRU缓存是面试中很容易考到的一个知识点,除了要对其原理熟悉之外,也要掌握其简单实现。通过采用两个hash map + list的数据结构,可以在O(1)的时间复杂度下实现get和put操作。

class LRUCache {
private:
int size;
list<int> lru;   //key
unordered_map<int, list<int>::iterator> map;  //key, iterator
unordered_map<int, int> kv;   //key, value

void update(int key) {
if (kv.find(key) != kv.end())
lru.erase(map[key]);
lru.push_front(key);
map[key] = lru.begin();
}

void evict() {
map.erase(lru.back());
kv.erase(lru.back());
lru.pop_back();
}

public:
LRUCache(int capacity) {
size = capacity;
}

int get(int key) {
if (kv.find(key) == kv.end())
return -1;
update(key);
return kv[key];
}

void put(int key, int value) {
if (kv.size() == size && kv.find(key) == kv.end())
evict();
update(key);
kv[key] = value;
}
};

/**
* 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);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐