LeetCode-LRU Cache-LRU缓存-DS
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 来当做时间。
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)); } };