zoukankan      html  css  js  c++  java
  • 【Leetcode】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.

    双向链表 + hash map

     1 class LRUCache{
     2 public:
     3     LRUCache(int capacity) {
     4         this->capacity = capacity;
     5     }
     6     
     7     int get(int key) {
     8         if (cache_map.find(key) != cache_map.end()) {
     9             cache_list.splice(cache_list.begin(), cache_list, cache_map[key]);
    10             cache_map[key] = cache_list.begin();
    11             return cache_map[key]->value;
    12         } else {
    13             return -1;
    14         }
    15     }
    16     
    17     void set(int key, int value) {
    18         if (cache_map.find(key) != cache_map.end()) {
    19             cache_list.splice(cache_list.begin(), cache_list, cache_map[key]);
    20             cache_map[key] = cache_list.begin();
    21             cache_map[key]->value = value;
    22         } else {
    23             if (cache_list.size() == capacity) {
    24                 cache_map.erase(cache_list.back().key);
    25                 cache_list.pop_back();
    26             }
    27             cache_list.push_front(cacheNode(key, value));
    28             cache_map[key] = cache_list.begin();
    29         }
    30     }
    31 private:
    32     struct cacheNode {
    33         int key;
    34         int value;
    35         cacheNode(int key, int value) : key(key), value(value) {}
    36     };
    37     
    38     int capacity;
    39     unordered_map<int, list<cacheNode>::iterator> cache_map;
    40     list<cacheNode> cache_list;
    41 };
  • 相关阅读:
    Rabbitmq
    Python() with语法糖
    Python()-类的专有方法之双下划线方法
    git配置踩过的坑
    https 协议 和 ssh 协议在使用上的差别
    Definite dimensionality
    java中定义和声明的区别
    数据库中表的数据逻辑删除的方案
    StringBuffer、StringBuilder和String的区别?
    常量池中的String与堆中的String
  • 原文地址:https://www.cnblogs.com/dengeven/p/4004020.html
Copyright © 2011-2022 走看看