leetcode 146. LRU缓存机制

assign() 给list赋值 
back() 返回最后一个元素 
begin() 返回指向第一个元素的迭代器 
clear() 删除所有元素 
empty() 如果list是空的则返回true 
end() 返回末尾的迭代器 
erase() 删除一个元素 
front() 返回第一个元素 
get_allocator() 返回list的配置器 
insert() 插入一个元素到list中 
max_size() 返回list能容纳的最大元素数量 
merge() 合并两个list 
pop_back() 删除最后一个元素 
pop_front() 删除第一个元素 
push_back() 在list的末尾添加一个元素 
push_front() 在list的头部添加一个元素 
rbegin() 返回指向第一个元素的逆向迭代器 
remove() 从list删除元素 
remove_if() 按指定条件删除元素 
rend() 指向list末尾的逆向迭代器 
resize() 改变list的大小 
reverse() 把list的元素倒转 
size() 返回list中的元素个数 
sort() 给list排序 
splice() 合并两个list 
swap() 交换两个list 
unique() 删除list中重复的元素

class LRUCache {
public:
    list<pair<int,int>> cache;
    unordered_map<int, list<pair<int, int>>::iterator> mp;
    int cap;
    LRUCache(int capacity) {
        cap=capacity;
    }
    
    int get(int key) {
        auto t=mp.find(key);
        if(t != mp.end())
        {
            pair<int,int> tmp=*mp[key];
            cache.erase(mp[key]);
            cache.push_front(tmp);
            mp[key]=cache.begin();
            return tmp.second;
        }
        return -1;
    }
    
    void put(int key, int value) {
        auto t=mp.find(key);
        if(t != mp.end())
        {
            cache.erase(mp[key]);
            cache.push_front(make_pair(key,value));
            mp[key]=cache.begin();
        }
        else
        {
            if(cache.size() == cap)
            {
                pair<int,int> tmp=cache.back();
                mp.erase(tmp.first);
                cache.pop_back();
                cache.push_front(make_pair(key,value));
                mp[key]=cache.begin();
            }
            else
            {
                cache.push_front(make_pair(key,value));
                mp[key]=cache.begin();
            }
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值