146. LRU Cache[hard]

146. LRU Cache 

  • Total Accepted: 86514
  • Total Submissions: 545459
  • Difficulty: Hard

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.


很简单的题目

用三个map分别装:

1、Cache里面的数据

2、每个数据最后的更新时间(used_time)

3、每个时间分别对哪个数据进行了操作(note)


对于每一个操作维护好这三个map就行


class LRUCache{
private:
    int Capacity;
    int Clock = 0;
    map <int , int > Cache;
    map <int , int > used_time;
    map <int , int > note;
public:
    
    
    LRUCache(int capacity) 
    {
        Capacity = capacity;
        Clock = 0;
    }
    
    void note_check()
    {
        while( Cache.count( note.begin()->second ) == 0 || 
                used_time[ note.begin()->second ] != note.begin()->first    )
            note.erase( note.begin() );
    }
    
    void check()
    {
        note_check();
        while( Cache.size() > Capacity )
        {
            int x = note.begin()->second;
            Cache.erase(x);
            used_time.erase(x);
            note.erase( note.begin() );
            note_check();
        }
    }
    
    int get(int key) 
    {
        ++Clock;
        if(Cache.count(key)!=0)
        {
            used_time[key] = Clock;
            note[Clock] = key;
            note_check();
            return Cache[key];
        }
        return -1;
    }
    
    void set(int key, int value) {
        ++Clock;
        Cache[key] = value;
        used_time[key] = Clock;
        note[Clock] = key;
        check();
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值