Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save superlayone/9884945 to your computer and use it in GitHub Desktop.

Select an option

Save superlayone/9884945 to your computer and use it in GitHub Desktop.
设计一个LRU缓存

设计一个LRU缓存,支持如下操作

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.

思路

哈希表存储映射关系可以在O(1)时间内实现快速查找,利用双向链表存储节点信息,O(1)时间内交换节点。头结点保存最近使用的,尾节点保存最近最少使用的,get时更新最近使用节点(即将当前节点更新至头结点)

	class LRUCache{
	public:
	    LRUCache(int capacity) {
	        cacheCapacity = capacity;
	    }
	    
	    int get(int key) {
	        if(cacheCapacity <0 ){
	            return -1;
	        }else{
	            if(cacheMap.find(key) == cacheMap.end()){
	                //no such key in map
	                return -1;
	            }
	            //add current node to head
	            cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]);
	            //update map
	            cacheMap[key] = cacheList.begin();
	            return cacheMap[key]->val;
	        }
	    }
	    
	    void set(int key, int value) {
	        //not found
	        if(cacheMap.find(key) == cacheMap.end()){
	            if(cacheCapacity == cacheList.size()){
	                //update map
	                cacheMap.erase(cacheList.back().key);
	                //update list
	                cacheList.pop_back();
	            }
	            //add a new node
	            cacheList.push_front(cacheNode(key,value));
	            //update map
	            cacheMap[key] =cacheList.begin();
	        }else{
	            //just ahead this node to front
	            cacheMap[key]->val = value;
	            cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]);
	            cacheMap[key] = cacheList.begin();
	        }
	    }
	private:
	    struct cacheNode{
	        int key;
	        int val;
	        cacheNode(int k,int v):key(k),val(v){}
	    };
	    list<cacheNode> cacheList;
	    unordered_map<int,list<cacheNode>::iterator> cacheMap;
	    int cacheCapacity;
	};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment