码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ - LRU Cache

时间:2014-05-16 05:42:29      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   c   

题目: 

  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.

解题思路:

  每一个Cache行有三个域(key, value, update_cnt);

  用unordered_map来存储Cache体;

  用queue来保存使用的历史信息。

代码:

  

bubuko.com,布布扣
struct Line {
    int key;
    int value;
    int update_cnt;
};

class LRUCache{
public:
    int capacity;
    unordered_map<int, Line> cache;
    queue<Line> q;
    LRUCache(int capacity) {
        this->capacity = capacity;
    }

    int get(int key) {
        if (cache.count(key)) {
            cache[key].update_cnt++;
            q.push(cache[key]);
            return cache[key].value;
        }
        return -1;
    }

    void set(int key, int value) {
        if (cache.count(key)) {
            cache[key].value = value;
            cache[key].update_cnt++;
            q.push(cache[key]);
        }
        else {
            if (cache.size() == capacity) {
                Line tmp;
                while (!q.empty()) {
                    tmp = q.front();
                    q.pop();

                    if (cache.count(tmp.key) && tmp.update_cnt == cache[tmp.key].update_cnt) {
                        break;
                    }
                }
                cache.erase(cache.find(tmp.key));
                cache[key].key = key;
                cache[key].value = value;
                cache[key].update_cnt = 0;
                q.push(cache[key]);
                return;
            }
            cache[key].key = key;
            cache[key].value = value;
            cache[key].update_cnt = 0;
            q.push(cache[key]);
        }
    }
};
bubuko.com,布布扣

 

LeetCode OJ - LRU Cache,布布扣,bubuko.com

LeetCode OJ - LRU Cache

标签:des   style   blog   class   code   c   

原文地址:http://www.cnblogs.com/dongguangqing/p/3726319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!