Using queues ans maps


#1

int c;
unordered_map<int,int> mp;
int count1;
queue q;
LRUCache::LRUCache(int capacity) {
c=capacity;
mp.clear();
int a=0;
count1=a;
queue empty;
swap(q,empty);
}

int LRUCache::get(int key) {
if(mp.find(key)==mp.end())
return -1;
else
{
queue q1;
while(!q.empty()){
if(q.front()==key){
q.pop();
continue;
}
else
{
q1.push(q.front());
q.pop();
}
}

       q=q1;
       
       q.push(key);
        return mp[key];
    }

}

void LRUCache::set(int key, int val) {
if(mp.find(key)!=mp.end()){
mp[key]=val;
queue q1;
while(!q.empty()){
if(q.front()==key){
q.pop();
continue;
}
else
{
q1.push(q.front());
q.pop();
}
}

      q=q1;
       
      q.push(key);
    
}
else if(count1>=c){
    mp.erase(q.front());
    q.pop();
    mp[key]=val;
    q.push(key);
    count1++;
}
else{
 
  
    mp[key]=val;
    count1++;
    q.push(key);
    
}

}