146. 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.

Subscribe to see which companies asked this question

解题思路

数据结构:双向链表,map
用map存储每次加入和更改的节点信息,这样可以保证在O(1)的时间get到key。
每次被访问或者新加入的节点放到链表尾,当超过最大数目时,从链表头部淘汰。

代码

struct Node{
    int key;
    int val;
    Node *prev;
    Node *next;

    Node(int key, int val): key(key), val(val), prev(NULL), next(NULL) {}
};

class LRUCache{
public:
    Node *head;
    Node *tail;
    map<int, Node*> m;
    int max_cap;
    int cur_cap;

    void move2tail(Node *node){
        //如果cache hit,先删除
        if (NULL != m[node->key]){
            node->prev->next = node->next;
            node->next->prev = node->prev;  
        }
        //再添加到链表尾
        node->prev = tail->prev;
        node->next = tail;
        tail->prev->next = node;
        tail->prev = node;
    }

    LRUCache(int capacity) {
        //这里定义了链表头和尾,也可以不要
        head = new Node(-1, -1);
        tail = new Node(-1, -1);
        head->next = tail;
        tail->prev = head;
        max_cap = capacity;
        cur_cap = 0;
    }

    int get(int key) {
        //cache miss
        if (NULL == m[key])
            return -1;
        //cache hit
        Node *node = m[key];
        move2tail(node);
        return node->val;
    }

    void set(int key, int value) {
        if (NULL == m[key]){
            if (cur_cap == max_cap)
            {
                m[head->next->key] = NULL;
                //删除第一个结点,也就是head->next
                Node *prev = head->next->prev;
                Node *next = head->next->next;
                prev->next = next;
                next->prev = prev;
            }
            //新增一个节点,并添加到链表尾
            Node *node = new Node(key, value);
            move2tail(node);
            m[key] = node;//更新map
            if(cur_cap < max_cap)
                cur_cap++;
        }
        else
        {
            Node *node = m[key];
            node->val = value;
            move2tail(node);
        }

    }
};

参考资料

语言链接
c++http://www.cnblogs.com/ganganloveu/p/4108979.html
javahttp://www.cnblogs.com/yrbbest/p/4489577.html
pythonhttp://www.jianshu.com/p/32e38137ec50
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值