Leet Code LRU Cache

Q:

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.

  

    首先我们要了解什么是LRU算法? LRU是Least Recently Used的缩写,即最少使用页面置换算法,是为虚拟页式存储管理服务的。通俗点说就是当内存满了之后将最近最少使用的数据丢掉,这样现在来的数据就能放进内存。

Cache(高速缓存), 一个在计算机中几乎随时接触的概念。CPU中Cache能极大提高存取数据和指令的时间,让整个存储器(Cache+内存)既有Cache的高速度,又能有内存的大容量;操作系统中的内存page中使用的Cache能使得频繁读取的内存磁盘文件较少的被置换出内存,从而提高访问速度;数据库中数据查询也用到Cache来提高效率;即便是Powerbuilder的DataWindow数据处理也用到了Cache的类似设计。Cache的算法设计常见的有FIFO(first in first out)和LRU(least recently used)。根据题目的要求,显然是要设计一个LRU的Cache。

该题的要求是设计一个数据结构,需要有两个方法:get(), set()。get()顾名思义,set()要注意的是当初始给定的大小满了时,这个时候就需要将最近最少使用的节点删除,新的节点再放进去。


网上有很多解法,比如双链表解法,但是这种我自己实现了之后超时,于是采用map来做。

因为map在插入节点的时候会根据key的值自动排序,所以我们可以利用这点,设计一个map,以count(使用度或者可以说优先级)和key为键值对,根据count排序,当空间满了之后只要将最后一个即count最小的节点删掉,将新的节点加进去就行,而且每次get()之后就要将get的节点的count值更新,应该是将它放到头部,新加入的节点也放在头部,这些我们都用一个成员变量count来控制。

代码:

 

struct node {
    int value, count;		//count为该节点的使用情况,count越大使用越频繁
    node(int v, int c) : value(v), count(c) {}
};
class LRUCache{//a way to improve effeiciency is to use list rather than map to store count numbers. and use hashtable
public:
    int count, cap, sz;		//count为成员变量,后来的节点的count值初始就比前面的count大
    map<int, int> ck;		//count, key 插入一个新节点时会根据count排序,容量不够时把begin()删除即可,后插入的节点count比前面插入的要大
							//因为map中是根据'键'来排序,所以该map中只能是count - key键值对, 如果要删除必须根据count删除,此时就需要根据kv中key来获得node的count拷贝
    map<int, node> kv;		//key, node<value, count>
    LRUCache(int capacity) : count(0x80000000), cap(capacity), sz(0){
        
    }
    
    int get(int key) {
        if(cap <= 0)
            return -1;
        map<int, node>::iterator p = kv.find(key);
        if(p != kv.end()) {
            ++count;
			ck.erase(p->second.count);			//根据p的count值将ck中的count记录删掉,以便后面可以重新在ck中插入新的count,key键值对,下面同理
			p->second.count = count;
            ck.insert(pair<int, int>(count, key));
			return p->second.value;
        } else {
            return -1;
        }
    }
    
    void set(int key, int value) {
        if(cap <= 0)
            return;
        ++count;
        map<int, node>::iterator p = kv.find(key);
        if(p != kv.end()) {			
            ck.erase(p->second.count);
			p->second.count = count;
            ck.insert(pair<int, int>(count, key));
			p->second.value = value;
        } else {
            if(sz < cap) {
                kv.insert(pair<int, node>(key, node(value, count)));
                ck.insert(pair<int, int>(count ,key));
                ++sz;
            } else {
				int tmpKey = ck.begin()->second;	//key
                kv.erase(tmpKey);
                ck.erase(ck.begin());
                kv.insert(pair<int, node>(key, node(value, count)));
                ck.insert(pair<int, int>(count ,key));	
            }
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
探险家小扣的行动轨迹,都将保存在记录仪中。expeditions[i] 表示小扣第 i 次探险记录,用一个字符串数组表示。其中的每个「营地」由大小写字母组成,通过子串 -> 连接。例:"Leet->code->Campsite",表示到访了 "Leet"、"code"、"Campsite" 三个营地。expeditions[0] 包含了初始小扣已知的所有营地;对于之后的第 i 次探险(即 expeditions[i] 且 i > 0),如果记录中包含了之前均没出现的营地,则表示小扣 新发现 的营地。 请你找出小扣发现新营地最多且索引最小的那次探险,并返回对应的记录索引。如果所有探险记录都没有发现新的营地,返回 -1。注意: 大小写不同的营地视为不同的营地; 营地的名称长度均大于 0。用python实现。给你几个例子:示例 1: 输入:expeditions = ["leet->code","leet->code->Campsite->Leet","leet->code->leet->courier"] 输出:1 解释: 初始已知的所有营地为 "leet" 和 "code" 第 1 次,到访了 "leet"、"code"、"Campsite"、"Leet",新发现营地 2 处:"Campsite"、"Leet" 第 2 次,到访了 "leet"、"code"、"courier",新发现营地 1 处:"courier" 第 1 次探险发现的新营地数量最多,因此返回 1。示例 2: 输入:expeditions = ["Alice->Dex","","Dex"] 输出:-1 解释: 初始已知的所有营地为 "Alice" 和 "Dex" 第 1 次,未到访任何营地; 第 2 次,到访了 "Dex",未新发现营地; 因为两次探险均未发现新的营地,返回 -1
最新发布
04-23

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值