LeetCode LRU Cache STL

来源:互联网 发布:淘宝店铺取名字 编辑:程序博客网 时间:2024/06/06 05:35

思路:

LRU算法的STL实现:list + unordered_map

list:双向链表;顺序存储;如果已知一个元素可以在O(1)的时间范围内插入或者删除,但不能随机查找。

Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.They are very similar to forward_list: The main difference being that forward_list objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.Compared to other base standard sequence containers (array, vector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements).

API:
std::list::spice
Transfers elements from x into the container, inserting them at position.

entire list (1)     void splice (const_iterator position, list& x);    void splice (const_iterator position, list&& x);single element (2)          void splice (const_iterator position, list& x, const_iterator i);    void splice (const_iterator position, list&& x, const_iterator i);element range (3)       void splice (const_iterator position, list& x,                 const_iterator first, const_iterator last);    void splice (const_iterator position, list&& x,                 const_iterator first, const_iterator last);

std::unordered_map:哈希表

Unordered maps are associative containers that store elements formed by the combination of a key value and a mapped value, and which allows for fast retrieval of individual elements based on their keys.In an unordered_map, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. Types of key and mapped value may differ.Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.Unordered maps implement the direct access operator (operator[]) which allows for direct access of the mapped value using its key value as argument.
struct CacheNode {    int key;    int value;    CacheNode(int k, int v) : key(k), value(v) {    }};class LRUCache{private:    int size;    list<CacheNode> cacheList;    unordered_map<int, list<CacheNode>::iterator> cacheMap;public:    LRUCache(int capacity) {        size = capacity;    }    int get(int key) {        if(cacheMap.find(key) == cacheMap.end()) {            return -1;        }else {            auto it = cacheMap[key];            cacheList.splice(cacheList.begin(), cacheList, it);            cacheMap[key] = cacheList.begin();            return cacheList.begin()->value;        }    }    void set(int key, int value) {        //not found        if(cacheMap.find(key) == cacheMap.end()) {            if(cacheList.size() == size) {                cacheMap.erase(cacheList.back().key);                cacheList.pop_back();            }            cacheList.push_front(CacheNode(key, value));            cacheMap[key] = cacheList.begin();        }else { // found            auto it = cacheMap[key];            cacheList.splice(cacheList.begin(), cacheList, it);            cacheMap[key] = cacheList.begin();            cacheList.begin()->value = value;        }    }};
0 0
原创粉丝点击