Leetcode之LRU Cache

题目:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

The cache is initialized with a positive capacity.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

代码:

方法一——map,vector:

class LRUCache {
public:
    LRUCache(int capacity) {
        cap = capacity, cur = 0; //cur表示已存放的容量
    }
    
    int get(int key) {
        vector<int>::iterator it = find(v.begin(), v.end(), key); //在vector中找对应的key
        if(it == v.end()) return -1; 
        v.erase(it); 
        v.emplace_back(key); //每次get都将该key置顶
        return m[key];
    }
    
    void put(int key, int value) {
        if(m[key])  //如果原先key中就有值,则覆盖原值,同时置顶该key
        {
            m[key] = value;
            vector<int>::iterator it = find(v.begin(), v.end(), key);
            v.erase(it);
            v.emplace_back(key);
            return;
        }
                
        if(cur == cap)
        {
            int p = v.front();
            m[p] = 0;
            v.erase(v.begin());
            m[key] = value;
            v.emplace_back(key);
        }
        else
        {
            cur++;
            v.emplace_back(key);
            m[key] = value;
        }
    }
    int cap, cur;
    vector<int> v;
    map<int, int> m;
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

方法二——双向链表:

class LRUCache {
private:
	int capacity;
	int capacity_cur;
	typedef struct ListNode
	{
		int key;
		int value;
		struct ListNode* next;
		struct ListNode* pre;
		ListNode(int k , int v):key(k),value(v),next(NULL),pre(NULL) {}
	}ListNode;
	ListNode *head;
	
	typedef struct Value
	{
		int val;
		ListNode *p;
		Value(int _v,ListNode *pp):val(_v),p(pp){}
		Value() {}  //if this constructor is not defined,there will be wrong
	}tValue;
	map< int,tValue > mkv;
	map< int,tValue > :: iterator it;
public:
    LRUCache(int capacity) {
       this->capacity = capacity;
		head = new ListNode(0,0);
		capacity_cur = 0;
    }
    
    int get(int key) {
       if( is_exist(key) )  
		{
			//get down the loc node
			ListNode *loc = mkv[key].p;
			loc->pre->next = loc->next;
			loc->next->pre = loc->pre;
 
			//insert into the front of the head
			loc->next = head->next;
			loc->pre = head;
			head->next = loc;
			loc->next->pre = loc;
 
			return mkv[key].val;
		}
		else
		{
			return -1;
		}
    }
    
    void put(int key, int value) {
       if(  is_exist(key) ) 
		{
			mkv[key].val = value;
			ListNode *q = mkv[key].p;
			q->value = value;
           
            ListNode *loc = mkv[key].p;
			loc->pre->next = loc->next;
			loc->next->pre = loc->pre;
 
			//insert into the front of the head
			loc->next = head->next;
			loc->pre = head;
			head->next = loc;
			loc->next->pre = loc;
			return ;
		}
 
		ListNode *tmp = new ListNode(key,value);
		if(capacity_cur<capacity)
		{
			if(head->next==NULL) //the list is empty
			{
				head->next = tmp ;
				head->pre = tmp;
				tmp->next = head;
				tmp->pre = head;
				tValue tv(value,tmp);
				mkv[key] = tv;
				++capacity_cur;
			}
			else //insert the tmp into the front of the list
			{
				tmp->next = head->next;
				tmp->pre = head;
				head->next->pre = tmp;
				head->next = tmp;
				tValue tv(value,tmp);
				mkv[key] = tv;
				++capacity_cur;
			}
		}
		else
		{
			//get rid of the lru node
			ListNode *tail = head->pre;
			head->pre = tail->pre;
			tail->pre->next = head;
			mkv.erase(tail->key);
			delete tail;
		
			//insert into the new node
			tmp->next = head->next;
			tmp->pre = head;
			head->next->pre = tmp;
			head->next = tmp;
			tValue tv(value,tmp);
			mkv[key] = tv;
		}
    }
    bool is_exist(int key)
	{
		return ( mkv.find(key) != mkv.end() );
	}
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值