Friday, January 23, 2015

LRU Cache

Q:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

T:
Store the data in a list. Move an item to the front of the list when that item is accessed. Use a hittable to store the mapping from the key to the iterator in the list;

A:


class LRUCache{
private:
    class entry {
        public:
        int key;
        int value;
    };
    int cap;
    list< entry > data;
    unordered_map< int, list< entry >::iterator > mp;
public:
    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
        if(mp.find(key) != mp.end()) {
            if(mp[key] != data.begin()) {
                entry item = *(mp[key]);
                data.erase(mp[key]);
                data.push_front(item);
                mp[key] = data.begin();
            }
            return data.front().value;
        }
        return -1;
    }
    
    void set(int key, int value) {
        if(mp.find(key) != mp.end()) {
            if(mp[key] != data.begin()) {
                entry item = *(mp[key]);
                data.erase(mp[key]);
                data.push_front(item);
                mp[key] = data.begin();
            }
            data.front().value = value;
            return;
        }
        if(data.size() >= cap) {
            mp.erase(data.back().key);
            data.pop_back();
        }
        entry item;
        item.key = key;
        item.value = value;
        data.push_front(item);
        mp[key] = data.begin();
    }
};

No comments:

Post a Comment