leetcode LRU Cache

题目大意就是使用最近最少使用算法(LRU)来实现一个读取和写入值的数据结构。主要注意点在于链表和map的使用,map插入和寻找数据的操作都是O(logn),可以帮助迅速定位链表中的位置。每次读取数据时,都要将链表的该节点移到链表的前端,并修改map中的value值,当需要插入数据且链表满的时候,删除链表的最后一个数据,删除map中的对应的key,最后在链表前端插入数据,然后map存储对应位置信息。

#include <list>
#include <iostream>
#include <map>
using namespace std;
class Key
{
public:
    int key,value;
    Key():key(0),value(0){};
    Key(int key, int value):key(key),value(value){};
};
class LRUCache{
private:
    int size;
    int capacity;
    list<Key> cache;
    map< int, list<Key>::iterator > search;
public:
    LRUCache(int capacity) 
    {
        size = 0;
        this->capacity = capacity;
    }
    int get(int key) 
    {
        map<int, list<Key>::iterator>::iterator it = search.find(key);
        if(it != search.end())
        {
            int value = it->second->value;
            cache.erase(it->second);
            cache.insert(cache.begin(),Key(key, value));
            it->second = cache.begin();
            return value;
        }
        return -1;
    }
    void set(int key, int value)
    {
        map<int, list<Key>::iterator>::iterator it = search.find(key);
        if(it != search.end())
        {
            cache.erase(it->second);
            cache.insert(cache.begin(), Key(key, value));
            it->second = cache.begin();
            return;
        }
        else
        {
            if(size < capacity)
            {
                size++;
                cache.insert(cache.begin(), Key(key, value));
                search.insert(map<int, list<Key>::iterator>::
                    value_type(key, cache.begin()));
            }
            else
            {
                search.erase(cache.rbegin()->key);
                cache.pop_back();
                cache.insert(cache.begin(), Key(key, value));
                search.insert(map<int, list<Key>::iterator>::
                    value_type(key, cache.begin()));
            }
        }
    }
};

int main()
{

    LRUCache lru(1);
    lru.set(2, 1);
    cout << lru.get(2) << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值