SalmaYasser

LRU

Dec 18th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. class LRUCache {
  2. public:
  3. list <pair <int , int>> cach ;
  4. int lim ;
  5. unordered_map <int , list <pair <int , int>> :: iterator> key_pointer;
  6.  
  7. LRUCache(int capacity) {
  8. lim = capacity;
  9.  
  10. }
  11.  
  12. int get(int key) {
  13.  
  14. if (key_pointer.count (key) == 0)
  15. return -1;
  16.  
  17. list <pair <int , int>> :: iterator it = key_pointer[key];
  18.  
  19. int res = (*it).second;
  20.  
  21. cach.push_front ( { (*it).first, (*it).second});
  22. key_pointer[key] = cach.begin();
  23.  
  24. cach.erase(it);
  25.  
  26. return res;
  27. }
  28.  
  29. void put(int key, int value) {
  30.  
  31.  
  32. if (cach.size() == lim && key_pointer.count (key) == 0)
  33. {
  34.  
  35. pair <int , int> to_remove = cach.back();
  36.  
  37. key_pointer.erase(to_remove.first);
  38.  
  39. cach.pop_back();
  40.  
  41. }
  42.  
  43. if (key_pointer.count (key) > 0)
  44. {
  45. list < pair < int ,int> > :: iterator it = key_pointer[key];
  46. cach.erase(it);
  47.  
  48. }
  49.  
  50. cach.push_front ({key, value});
  51. key_pointer[key] = cach.begin();
  52.  
  53. }
  54. };
  55.  
  56. /**
  57. * Your LRUCache object will be instantiated and called as such:
  58. * LRUCache* obj = new LRUCache(capacity);
  59. * int param_1 = obj->get(key);
  60. * obj->put(key,value);
  61. */
  62.  
  63. /*
  64.  
  65. head return
  66. tail replaced
  67. O(1) to get val
  68.  
  69. map <int, addres>
  70.  
  71. creat 1
  72. head = 1 -> null
  73. 1 -> x
  74. tail = 1
  75.  
  76. creat 2
  77. head = 2 -> 1 -> head
  78. 2 -> y
  79.  
  80.  
  81.  
  82.  
  83.  
  84. */
Advertisement
Add Comment
Please, Sign In to add comment