Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. class LRUCache {
  2. private:
  3. int maxSize;
  4. list<pair<int,int> > cache;
  5. unordered_map<int, list<pair<int,int> >::iterator> m;
  6. public:
  7. LRUCache(int capacity): maxSize(capacity) {
  8.  
  9. }
  10.  
  11. int get(int key) {
  12. auto it = m.find(key);
  13. if(it == m.end()){
  14. return -1;
  15. }
  16. cache.push_front(*(it->second));
  17. cache.erase(it->second);
  18. m[key] = cache.begin();
  19. return it->second->second;
  20. }
  21.  
  22. void put(int key, int value) {
  23. auto it = m.find(key);
  24. if(it != m.end()){
  25. cache.erase(it->second);
  26. }
  27. cache.push_front({key,value});
  28. m[key] = cache.begin();
  29. if(cache.size() > maxSize){
  30. auto it = cache.rbegin();
  31. m.erase(it->first);
  32. cache.pop_back();
  33. }
  34. }
  35. };
  36.  
  37. /**
  38. * Your LRUCache object will be instantiated and called as such:
  39. * LRUCache* obj = new LRUCache(capacity);
  40. * int param_1 = obj->get(key);
  41. * obj->put(key,value);
  42. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement