leetcode:146. LRU缓存机制

146. LRU缓存机制

思路

一开始的思路是用map来保存每个keypair<value,顺序>,顺序是用1,2,3…来表示的,越后面越表示没被访问。每当执行getput的时候,访问的那个pair就移到1,它之前的页面就全往后移一位。这样也是能过简单的样例的,但是在最后几个样例会超时。因为它每次putget都会把所有的map遍历一遍,非常耗时。

所以就去看了题解,发现需要用到哈希表来解决搜索的问题,用双向列表来解决排列的问题。这方面详细的介绍就去看题解吧~

ac代码

class LRUCache {
public:
    int capacity;
    list<pair<int, int>> l;
    unordered_map<int, list<pair<int, int>>::iterator> hash;

    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
        auto a = hash.find(key);
        if(a == hash.end()) return -1;
        l.push_front(make_pair(hash[key]->first, hash[key]->second));
        l.erase(a->second);
        hash[key] = l.begin();
        return hash[key]->second;
    }
    
    void put(int key, int value) {
        auto a = hash.find(key);
        if(a != hash.end()){
            l.push_front(make_pair(key, value));
            l.erase(a->second);
            hash[key] = l.begin();
            return;
        }
        if(hash.size() == capacity){
            hash.erase(l.rbegin()->first);
            l.pop_back();
        }
        l.push_front(make_pair(key, value));
        hash[key] = l.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);
 */

超时代码

class LRUCache {
public:
    int capacity;
    map<int, pair<int, int>> m;

    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
        if(m.find(key) == m.end()) return -1;
        for(auto& p: m){
            if(p.second.second < m[key].second)
                p.second.second ++;
        }
        m[key].second = 1;
        return m[key].first;
    }
    
    void put(int key, int value) {
        if(m.find(key) != m.end()){
            for(auto& p: m){
                if(p.second.second < m[key].second)
                    p.second.second ++;
            }
            m[key] = make_pair(value, 1);
            return;
        }
        if(m.size() == capacity){
            for(auto& p: m){
                if(p.second.second == capacity){
                    m.erase(p.first);
                    break;
                }
            }
            for(auto& p: m)
                p.second.second ++;
            m[key] = make_pair(value, 1);
        }
        else{
            for(auto& p: m)
                p.second.second ++;
            m[key] = make_pair(value, 1);
        }
    }
};

/**
 * 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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值