LeetCode (26) LRU Cache,leetcodelru
題目描述
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.
題目要求我們實現一個快取資料結構。要求的主要操作為擷取(get)和插入(set)。需要注意的是,當緩衝滿了的時候,在set時需要刪除最長時間沒有使用的元素,並插入新元素。這就要求我們在資料結構中設計一個方法要麼記錄每個元素的被使用順序,要麼根據元素的被使用順序儲存元素。需要注意的是,在get元素的時候,如果元素存在於緩衝中,則該元素的被使用順序要被提前。
可以通過使用雙向鏈表表示緩衝中資料。鏈表的頭部表示最近被使用的元素,鏈表的尾部表示最長時間沒被使用的元素。當擷取/插入元素時,將元素放置在鏈表的頭部。需要注意的是,若插入的元素的key已經存在於緩衝中,則要刪除原來的資料(key, value)結點。
我們知道對鏈表進行隨機訪問的時間複雜度為O(n),那麼上面的資料結構每次獲得和插入元素的時間複雜度都為O(n)。為了減小時間複雜度,我們可以使用一個map結構,通過key儲存結點位置,時間複雜度為O(logn)。如果要求更高的時間效率還可以使用unordered_map取代map儲存結點位置。
map結構如下:
map<int, node*> cache;
根據上述思路得到的完整代碼如下:
struct node{ int key; int value; node* pre; node* next; node(int k, int v) :key(k), value(v), pre(NULL), next(NULL) {};};class LRUCache{private: int m_capacity; int m_size; node* m_head; node* m_tail; map<int, node*> m_cache;public: LRUCache(int capacity) { m_capacity = capacity; m_size = 0; m_head = new node(0, 0); m_tail = new node(0, 0); m_head->next = m_tail; m_tail->pre = m_head; m_cache.clear(); } ~LRUCache() { delete m_head; delete m_tail; map<int, node*>::iterator it; for (it = m_cache.begin(); it != m_cache.end(); ++it) { delete(it->second); } m_cache.clear(); } void putTohead(node* cur) { cur->next = m_head->next; cur->next->pre = cur; m_head->next = cur; cur->pre = m_head; } int get(int key) { map<int, node*>::iterator it = m_cache.find(key); if (it != m_cache.end()) { node* cur = it->second; cur->pre->next = cur->next; cur->next->pre = cur->pre; putTohead(cur); return cur->value; } else return -1; } void set(int key, int value) { map<int, node*>::iterator it = m_cache.find(key); if (it != m_cache.end()) { node* cur = it->second; cur->value = value; cur->pre->next = cur->next; cur->next->pre = cur->pre; putTohead(it->second); } else { node* new_node = new node(key, value); putTohead(new_node); m_cache[key] = new_node; if (m_size < m_capacity) m_size++; else { node* del = m_tail->pre; del->pre->next = m_tail; m_tail->pre = del->pre; it = m_cache.find(del->key); m_cache.erase(it); delete del; } } }};