LeetCode-LRU Cache-LRU缓存-DS
2014-10-02 18:06
330 查看
https://oj.leetcode.com/problems/lru-cache/
一道简单的考察数据结构的题目。
首先要理解什么是LRU。LRU是最近最少使用,也就是说时间戳上面更新最慢的那个,在capacity满的情况下需要被删除。
首先需要Get(key) = value的操作,这里需要一个map。
其次,需要一个对每个key的时间戳进行插入、删除、更新的操作,我选择了set,用pair作为时间戳、key的索引。
要快速的找到一个key在set中的位置,我又用了一个map。
插入时,更新<key,value> map, <key,time> map,并删除set中旧的排序结点,插入新的排序结点,通过<key,time>索引。
最后,引入一个long long unsigned 来当做时间。
一道简单的考察数据结构的题目。
首先要理解什么是LRU。LRU是最近最少使用,也就是说时间戳上面更新最慢的那个,在capacity满的情况下需要被删除。
首先需要Get(key) = value的操作,这里需要一个map。
其次,需要一个对每个key的时间戳进行插入、删除、更新的操作,我选择了set,用pair作为时间戳、key的索引。
要快速的找到一个key在set中的位置,我又用了一个map。
插入时,更新<key,value> map, <key,time> map,并删除set中旧的排序结点,插入新的排序结点,通过<key,time>索引。
最后,引入一个long long unsigned 来当做时间。
using namespace std; typedef pair<int,int> scpair; class LRUCache{ public: map <int,int> c; map <int,int> u; std::set <scpair,less<scpair>> s; int cap; long long unsigned ops; LRUCache(int capacity) { cap=capacity; ops=0; } int get(int key) { if (c.find(key)!=c.end()){ ops++; int old=u[key]; u[key]=ops; s.erase(scpair(old,key)); s.insert(scpair(ops,key)); return c[key]; } return -1; } void set(int key, int value) { ops++; if (c.find(key)!=c.end()){ c[key]=value; int old=u[key]; u[key]=ops; s.erase(scpair(old,key)); s.insert(scpair(ops,key)); return; } if (c.size()==cap){ //first delete scpair t=*s.begin(); s.erase(s.begin()); c.erase(c.find(t.second)); u.erase(u.find(t.second)); } c[key]=value; u[key]=ops; s.insert(scpair(ops,key)); } };
相关文章推荐
- LeetCode:146_LRU cache | LRU缓存设计 | Hard
- 【Leetcode】:LRU Cache_缓存淘汰算法LRU的设计与实现
- Leetcode 146 LRU Cache 模拟操作系统LRU
- LeetCode OJ 之 LRU Cache(LRU缓存)
- LeetCode: LRU Cache 最近最少使用算法 缓存设计
- leetcode LRU Cache(高级缓存的最近最少使用算法实现)
- [LeetCode] LRU Cache 缓存器
- LeetCode 146. LRU Cache(LRU缓存)
- LeetCode题解: LRU Cache 缓存设计
- [转]LRU缓存介绍与实现 (Java) .
- leetcode LRU Cache
- LRU缓存淘汰算法
- leetcode:LRU Cache
- [LeetCode]题解(python):146-LRU Cache
- LeetCode—LRU Cache解题报告
- LeetCode | LRU Cache
- LeetCode OJ LRU Cache
- leetcode-LRU Cache
- 使用LRU算法缓存图片
- 简单LRU算法实现缓存