您的位置:首页 > 其它

LeetCode OJ LRU Cache

2015-03-23 00:11 239 查看
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.
class LRUCache{
public:
    LRUCache(int capacity) {
        ca = capacity;
        global_vis = 0;
        now = 0;
        cache = new C[capacity];
        for (int i = 0; i < capacity; i++) cache[i].vis = -1;  // -1 means not visited yet
    }
    
    ~LRUCache() {
        delete []cache;
    }
    
    int get(int key) {
        global_vis++;  // run time recorder
        for (int i = 0; i < now; i++) {
            if (cache[i].k == key && cache[i].vis != -1) {  // find the key and it's used(may be there is a right key but not used at all)
                cache[i].vis = global_vis;
                return cache[i].v;
            }
        }
        return -1;
    }
    
    void set(int key, int value) {
        global_vis++;
        for (int i = 0; i < now; i++) {  // search it first, if the key exist, change the value and the visit moment
            if (cache[i].k == key) {
                cache[i].v = value;
                cache[i].vis = global_vis;
                return;
            }
        }
        if (now == ca) {  // if it's full(and the key is not found)
            int min = cache[0].vis;
            int pos = 0;
            for (int i = 0; i < ca; i++) {  // find the min visit cache
                if (min > cache[i].vis) {
                    min = cache[i].vis;
                    pos = i;
                }
            }
            cache[pos].k = key;  // change the min visit cache
            cache[pos].v = value;
            cache[pos].vis = global_vis;
        } else {  // not full yet(and the key is not found)
            cache[now].k = key;
            cache[now].vis = global_vis;
            cache[now++].v = value;  // add a new one
        }
    }
private:
    struct C {
        int vis;  // the visit moment, smaller means less recently used
        int k;
        int v;
    };
    C *cache;
    int ca;
    int now;  // the number of the cache right now
    int global_vis;  // a run time counter, help to record the visit moment
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: