leetcode LRU Cache
2014-04-13 17:04
323 查看
题目大意就是使用最近最少使用算法(LRU)来实现一个读取和写入值的数据结构。主要注意点在于链表和map的使用,map插入和寻找数据的操作都是O(logn),可以帮助迅速定位链表中的位置。每次读取数据时,都要将链表的该节点移到链表的前端,并修改map中的value值,当需要插入数据且链表满的时候,删除链表的最后一个数据,删除map中的对应的key,最后在链表前端插入数据,然后map存储对应位置信息。
#include <list> #include <iostream> #include <map> using namespace std; class Key { public: int key,value; Key():key(0),value(0){}; Key(int key, int value):key(key),value(value){}; }; class LRUCache{ private: int size; int capacity; list<Key> cache; map< int, list<Key>::iterator > search; public: LRUCache(int capacity) { size = 0; this->capacity = capacity; } int get(int key) { map<int, list<Key>::iterator>::iterator it = search.find(key); if(it != search.end()) { int value = it->second->value; cache.erase(it->second); cache.insert(cache.begin(),Key(key, value)); it->second = cache.begin(); return value; } return -1; } void set(int key, int value) { map<int, list<Key>::iterator>::iterator it = search.find(key); if(it != search.end()) { cache.erase(it->second); cache.insert(cache.begin(), Key(key, value)); it->second = cache.begin(); return; } else { if(size < capacity) { size++; cache.insert(cache.begin(), Key(key, value)); search.insert(map<int, list<Key>::iterator>:: value_type(key, cache.begin())); } else { search.erase(cache.rbegin()->key); cache.pop_back(); cache.insert(cache.begin(), Key(key, value)); search.insert(map<int, list<Key>::iterator>:: value_type(key, cache.begin())); } } } }; int main() { LRUCache lru(1); lru.set(2, 1); cout << lru.get(2) << endl; return 0; }
相关文章推荐
- LeetCode LRU Cache
- Leetcode LRU Cache
- leetcode 刷题:LRU cache
- LeetCode 之 LRU Cache Java实现
- [leetcode]LRU Cache @ Python
- leetcode :LRU Cache
- leetcode LRU Cache(高级缓存的最近最少使用算法实现)
- LeetCode LRU Cache
- leetcode_Design and implement a data structure for Least Recently Used (LRU) cache
- Leetcode LRU Cache
- LeetCode (26) LRU Cache
- Leetcode LRU Cache
- leetcode之LRU Cache
- Leetcode LRU Cache
- leetcode LRU Cache(**)
- LeetCode LRU Cache
- LeetCode LRU Cache
- leetcode LRU cache
- LeetCode LRU Cache 百度笔试
- LRU Cache leetcode