標籤:des style blog http color 使用 os strong
LeetCode: LRU Cache
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.
地址:https://oj.leetcode.com/problems/lru-cache/
演算法:根據題目的意思是讓我們類比LRU演算法(最近最常使用演算法)。採用一個鏈表list來表示cache,這樣方便刪除鏈表中的任意元素,以及插入前端節點元素。另外使用一個map來索引鏈表中的每一個關索引值,這樣能夠快速的找到鏈表中關索引值相對應的位置。演算法實現三個函數:第一個為建構函式,用來設定cache的容量;第二個get函數,用於取得關索引值key對應的value值,首先尋找cache,如果未找到該key值,返回-1,如果找到該key值,則將該key對應的元素移到鏈表的前端節點,並更新索引值;第三個函數為set函數,用於設定關索引值key對應的value值,首先尋找cache,如果找到該key值,則設定該key值對應的value值,並把該key值移到鏈表的頭部,並更新索引值,如果沒找到且cache容量還未到達最大值,則在鏈表的頭部插入該key值,並且插入該key值對應的索引值,如果沒找到且cache容量已經達到最大值,則根據LRU演算法原則,刪除鏈表的最後一個節點同時刪除其索引值,然後將該key值插入鏈表頭部,並插入索引值。代碼:
1 class LRUCache{ 2 public: 3 LRUCache(int capacity) { 4 cap = capacity; 5 } 6 7 int get(int key) { 8 map<int,Iter>::iterator it = index_map.find(key); 9 if(it == index_map.end()){10 return -1;11 }12 Iter p = it->second;13 int val = it->second->second;14 cache.push_front(*p);15 it->second = cache.begin();16 cache.erase(p);17 return val;18 }19 20 void set(int key, int value) {21 map<int,Iter>::iterator it = index_map.find(key);22 if (it != index_map.end()){23 cache.push_front(make_pair(key,value));24 cache.erase(it->second);25 it->second = cache.begin();26 return ;27 }28 if (cap > cache.size()){29 cache.push_front(make_pair(key,value));30 index_map[key] = cache.begin();31 return ;32 }33 index_map.erase(cache.back().first);34 cache.pop_back();35 cache.push_front(make_pair(key,value));36 index_map[key] = cache.begin();37 }38 typedef list<pair<int,int> >::iterator Iter;39 list<pair<int,int> > cache;40 map<int,Iter> index_map;41 int cap;42 };