zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    最近使用缓存的问题,看到key和value感觉可能就要使用map了。用一个list维护一个cache,然后map指向相应cache的每个节点。

    注意这里的最近使用,不管是get还是set都属于最近使用的范畴,代码如下所示:

     1 class LRUCache{
     2 struct cacheNode{
     3     int key;
     4     int val;
     5     cacheNode(int k, int v):
     6     key(k), val(v){}
     7 };
     8 public:
     9     LRUCache(int capacity) {
    10         size = capacity;
    11     }
    12     
    13     int get(int key) {
    14         if(cacheMap.find(key) != cacheMap.end()){
    15             auto it = cacheMap[key];
    16             cacheList.splice(cacheList.begin(), cacheList, it);
    17             cacheMap[key] = cacheList.begin();
    18             return cacheList.begin()->val;
    19         }else 
    20             return -1;
    21     }
    22     
    23     void set(int key, int value) {
    24         if(cacheMap.find(key) != cacheMap.end()){//list中存在该元素
    25             auto it = cacheMap[key];
    26             cacheList.splice(cacheList.begin(), cacheList, it);
    27             cacheMap[key] == cacheList.begin();
    28             cacheList.begin()->val = value;
    29         }else{                                  //list中不存在该元素
    30             if(cacheList.size() == this->size){
    31                 cacheMap.erase(cacheList.back().key);
    32                 cacheList.pop_back();
    33             }
    34             cacheList.push_front(cacheNode(key, value));
    35             cacheMap[key] = cacheList.begin(); 
    36         }
    37     }
    38 private:
    39     int size;
    40     list<cacheNode> cacheList;
    41     unordered_map<int , list<cacheNode>::iterator> cacheMap;
    42 };
  • 相关阅读:
    pc端布局方式
    idea中Git操作
    原型和原型链
    BFC块级格式上下文
    开发环境和生产环境
    webpack-dev-server报错
    es6类的继承
    js文件上传
    es6 字符串和数字常用方法
    es6 set容器和map容器
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5015836.html
Copyright © 2011-2022 走看看