LintCode_134 LRU Cache

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.

思路是用一个队列和哈希表来实现:

每次get或者set的时候, 先将key压入队列尾部,然后在哈希表中对应的key的访问次数+1;

如果满了,进行while循环:查看队列头部的元素, 如果访问次数>1,则说明后面还被访问过, 故弹出, 如果访问次数==1,则说明后面已经没有被访问过,所以弹出并且在哈希表中删掉key。如此, 可以保证做少被访问的元素被弹出(保证了访问次数相同的情况下,先进先出)


class LRUCache{
public:
    // @param capacity, an integer
    LRUCache(int capacity) {
        // write your code here
        this->capacity = capacity;
    }
    
    // @return an integer
    int get(int key) {
        // write your code here
        if (map.find(key) != map.end()) {
            que.push(key);
            map[key].second++;
            return map[key].first;
        } else {
            return -1;
        }
    }

    // @param key, an integer
    // @param value, an integer
    // @return nothing
    void set(int key, int value) {
        // write your code here
        que.push(key);
        if (map.find(key) != map.end()) {
            map[key].first = value;
            map[key].second++;
        } else {
            if (map.size() < capacity) {
                map[key] = make_pair(value, 1);
            } else {
                int least_recently_key = que.front();
                while (map[least_recently_key].second > 1) {
                      map[least_recently_key].second--;
                      que.pop();
                      least_recently_key = que.front();
                }
                que.pop();
                //cout<<"erase "<<least_recently_key<<endl;
                map.erase(least_recently_key);
                map[key] = make_pair(value, 1);
            }
        }
    }
private:
    int capacity;
    unordered_map<int, pair<int, int>> map;
    queue<int> que;
};








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值