ann8497

LRU cache

Sep 3rd, 2019
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. /*
  2.  An LRU Cache should support fast lookup. Apparently, in order to achieve fast lookup, we need to use Hashtable or HashMap.
  3.  
  4. Also, an LRU Cache requires that insert and delete operations should be in O(1) time. The obvious choice for this requirement is Linked List. Linked List support insert/delete operations in O(1) time if we have the reference of element.
  5.  
  6. While building an LRU cache requires that you think in terms of these two data structures. The reality is that these two data structures actually work coherently to achieve the design.
  7.  
  8. So, we are finalizing on these data structures: HashMap and Doubly Linked List
  9. */
  10.  
  11. #include<bits/stdc++.h>
  12. using namespace std;
  13.  
  14. unordered_map<int, list<int> :: iterator> mp;
  15. list<int>q;
  16. int sz;
  17. void insert(int x){
  18.    
  19.     // if not present
  20.     if(mp.find(x) == mp.end()){
  21.         if(q.size() == sz){
  22.             int last = q.back();
  23.             q.pop_back();
  24.             mp.erase(last);
  25.         }
  26.     }
  27.     // if present
  28.     else
  29.     mp.erase(x);
  30.    
  31.     q.push_front(x);
  32.     mp[x] = q.begin();
  33.    
  34.    
  35. }
  36.  
  37. void display(){
  38.    
  39.     for(auto it = q.begin(); it!=q.end(); it++)
  40.     cout<<*it<<" ";
  41. }
  42.  
  43. int main(){
  44.    
  45.     cin>>sz;
  46.     insert(1);
  47.     insert(2);
  48.     insert(3);
  49.     insert(1);
  50.     insert(4);
  51.     insert(5);
  52.     display();
  53.     return 0;
  54. }
Add Comment
Please, Sign In to add comment