• 刷题146. LRU Cache


    一、题目说明

    题目146. LRU Cache,设计并实现一个LRU Cache,支持get和put操作。难度是Medium!时间复杂度要求是O(1)。

    二、我的解答

    时间复杂度要求是O(1),只能通过hash实现。同时要维护一个容量capacity,当capacity满的时候,更新“最近最少使用的元素”。故需要Hash+LinkedList实现“哈希链表”。

    class LRUCache {
    	public:
    		struct Node{
    			int key,value;
    			Node* next,*pre;
    		};
    		Node* head,*rear;
    
    		LRUCache(int size){
    			capacity = size;
    			head = new Node();
    	        rear = new Node();
    	        head->pre = NULL;
    	        head->next = rear;
    	        rear->next = NULL;
    	        rear->pre = head;
    		}
    		int get(int key){
    			if(cache.find(key)==cache.end()) return -1;
    			Node* tmp = cache[key];
    
    			//移除该节点 
    	        tmp->pre->next = tmp->next;
    	        tmp->next->pre = tmp->pre;
    			
    			//插入链头 
    	        head->next->pre = tmp;
    	        tmp->next = head->next;
    	        tmp->pre = head;
    	        head->next = tmp;
    	        return tmp->value;
    		}
    		void lru_delete() {
    	        if(cache.size() == 0) return;
    	        Node* tmp = rear->pre;
    	        rear->pre = tmp->pre;
    	        tmp->pre->next = rear;
    	        cache.erase(tmp->key);
    	        delete tmp;
       		}
    		void put(int key,int value){
    			if(cache.find(key) != cache.end()) {
    				//key已存在于链表中,更新值 
    	            cache[key]->value = value;
    	            this->get(key);
    	            return;
            	}
    			
    			//插入链表中 
    	        if(cache.size() >= capacity) 
    				this->lru_delete();
    	        Node *tmp = new Node;
    	        tmp->key = key;
    	        tmp->value = value;
    	        tmp->pre = this->head;
    	        tmp->next = this->head->next;
    	        if(head->next != NULL) head->next->pre = tmp;
    	        this->head->next = tmp;
    	        cache.insert(pair<int, Node*>(key, tmp));
    		}
    	private:
    		map<int,Node*> cache;
    		//最大容量 
    		int capacity;
    };
    
    Runtime: 120 ms, faster than 46.13% of C++ online submissions for LRU Cache.
    Memory Usage: 38.1 MB, less than 74.39% of C++ online submissions for LRU Cache.
    

    三、优化措施

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    记一次性能优化经历
    把一个一中的字段更新另一个表中的t-sql
    Dapper 中使用sql in 关键字查询
    HTML5 学习笔记 应用程序缓存
    HTML5学习笔记 Web存储
    HTML5 学习笔记 表单属性
    HTML5学习笔记 Geolocation(地理定位)
    vim插件之delimitMate.vim
    vim 插件之 surround.vim
    vim 脚本之快速打印log
  • 原文地址:https://www.cnblogs.com/siweihz/p/12274298.html
Copyright © 2020-2023  润新知