Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class LRUCache {
- public:
- list <pair <int , int>> cach ;
- int lim ;
- unordered_map <int , list <pair <int , int>> :: iterator> key_pointer;
- LRUCache(int capacity) {
- lim = capacity;
- }
- int get(int key) {
- if (key_pointer.count (key) == 0)
- return -1;
- list <pair <int , int>> :: iterator it = key_pointer[key];
- int res = (*it).second;
- cach.push_front ( { (*it).first, (*it).second});
- key_pointer[key] = cach.begin();
- cach.erase(it);
- return res;
- }
- void put(int key, int value) {
- if (cach.size() == lim && key_pointer.count (key) == 0)
- {
- pair <int , int> to_remove = cach.back();
- key_pointer.erase(to_remove.first);
- cach.pop_back();
- }
- if (key_pointer.count (key) > 0)
- {
- list < pair < int ,int> > :: iterator it = key_pointer[key];
- cach.erase(it);
- }
- cach.push_front ({key, value});
- key_pointer[key] = cach.begin();
- }
- };
- /**
- * 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);
- */
- /*
- head return
- tail replaced
- O(1) to get val
- map <int, addres>
- creat 1
- head = 1 -> null
- 1 -> x
- tail = 1
- creat 2
- head = 2 -> 1 -> head
- 2 -> y
- */
Advertisement
Add Comment
Please, Sign In to add comment