SHARE
TWEET

Untitled

a guest Nov 19th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class LRUCache {
  5. public:
  6.     int nowfirst = 1, nowlast = 1, capacity;
  7.     unordered_map<int,int>cache,track;
  8.     LRUCache(int capacity) {
  9.         capacity = capacity ;
  10.     }
  11.    
  12.     int get(int key) {
  13.         if(cache.find(key) == cache.end())return -1;
  14.         return cache[key];
  15.     }
  16.  
  17.     void put(int key, int value) {
  18.         //if capacity is 0 no insert is gonna happen
  19.         if(capacity == 0)return;
  20.         //capacity exceeded
  21.         if(cache.size() == capacity){
  22.             //new key needs to be inserted
  23.             if(cache.find(key) == cache.end()){
  24.                 //erasing oldest key
  25.                 //finding oldest key
  26.                 auto it = cache.find(track[nowfirst]);
  27.                 //erasing oldest key-value from cache
  28.                 cache.erase(cache.find(*it));
  29.                 //erasing odlest key
  30.                 track.erase(it);
  31.                 //increasing firstnow
  32.                 firstnow++;
  33.             }else{
  34.                 //the new key is overriding
  35.                 cache[key] = value ; //override
  36.             }
  37.             return;
  38.         }
  39.         //capacity did not exceed and new entry
  40.         cache[key] = value ;
  41.         if(cache.size() == 0){ //first entry
  42.             track[nowfirst] = key;
  43.             nowfirst++;
  44.         }
  45.         track[nowlast] = key;
  46.         nowlast++;
  47.         }
  48. };
  49.  
  50. /**
  51.  * Your LRUCache object will be instantiated and called as such:
  52.  * LRUCache* obj = new LRUCache(capacity);
  53.  * int param_1 = obj->get(key);
  54.  * obj->put(key,value);
  55.  */
  56.  
  57. int main(){
  58.     cout<<"hello"<<endl;
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top