class DS {
      public:
          int value;
          list<int>::iterator itr;
      };
      class LRUCache {
      public:
          int capacity;
          list<int> Queue;
          unordered_map<int, DS> HashMap;
          LRUCache(int capacity) {
              this->capacity = capacity;
          }
          int get(int key) {
              if(!HashMap.count(key)) {
                  return -1;
              }
              int value = HashMap[key].value;
              put(key, value);
              return value;
          }
          void put(int key, int value) {
              if(HashMap.count(key)) {
                  Queue.erase(HashMap[key].itr);
                  HashMap.erase(key);
              }
              if(Queue.size() == capacity) {
                  HashMap.erase(Queue.back());
                  Queue.pop_back();
              }
              Queue.push_front(key);
              HashMap[key] = {value, Queue.begin()};
          }
      };
      
      Cpp language logo

      LRU Cache

      LRU cache code

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.