Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time complexity :complexity of erase only
- we created a cache list of pair which will keep key and value pairs and we are keeping address of that pair of cache ie. list in map
- whose key will be actual key of that pair.
- we will keep our cache as most recent accesed element at front and least recent accessed element at back of cache.
- refreshposition will adjust position of an internal node in cache ie. node that is not in front nor in back to front.
- */
- class LRUCache{
- private:
- list<pair<int,int>> cache;
- unordered_map<int,list<pair<int,int>>::iterator> mymap; //Key, address in cache array ie. our cache memory
- int capacity;
- public:
- void refreshPosition(int key,int value){
- cache.erase(mymap[key]);
- cache.push_front(make_pair(key,value));
- mymap[key] = cache.begin(); //Addr of new position stored in map
- }
- LRUCache(int cap){
- this->capacity = cap;
- }
- int get(int key){
- if(mymap.find(key)!=mymap.end()){
- refreshPosition(key,(*mymap[key]).second); //just because it has been hit,so it's most recently used so updation.here start is used because
- //mymap[key] gives the addresss of that pair,and * at begining means that pair.
- return (*mymap[key]).second; //returning value for the key
- }
- return -1;
- }
- void set(int key, int value){
- if(mymap.find(key)!=mymap.end())
- refreshPosition(key,value); //if present in the cache,then updating the position to front of the cache
- else{ //if not present in cache,then adding it into cache and at the front of the cache
- cache.push_front(make_pair(key,value));
- mymap[key] = cache.begin();
- if(mymap.size()>capacity){ //if capacity exceeds,removing element from the back.
- mymap.erase(cache.back().first);
- cache.pop_back();
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement