class LRUCache{ public: typedef std::pair<int, int> ENTRY; LRUCache(int capacity) { max = capacity; count = 0; } int get(int key) { if(map.find(key)==map.end()) return -1; else { entry.splice(entry.begin(), entry, map[key]); return (map[key])->second; } } void set(int key, int value) { if(map.find(key)==map.end()) { entry.push_front(ENTRY(key, value)); map[key] = entry.begin(); if(++count>max) { int tmp = entry.back().first; entry.erase(--entry.end()); count--; map.erase(tmp); } } else { entry.splice(entry.begin(), entry, map[key]); map[key]->second = value; } } int count; int max; std::list<std::pair<int, int>> entry; std::unordered_map<int, std::list<std::pair<int, int>>::iterator> map; };
Friday, January 24, 2014
[LeetCode] LRU Cache
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment