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.

     就是设计一个数据结构,模拟缓存的操作。

    一开始想到使用队列,但是TLE。

    后来考虑到每次淘汰cache时,我只需要知道最旧的那个cache,而不需要知道具体的cache的排序,想到

    一个数据结构,堆。设置一个index,表示cache插入的顺序。维持一个index作为特征值的堆。

    在具体实现时,用一个HashMap存储key和该堆中节点的对应关系。这样,每次

    淘汰时,只需将堆头淘汰掉,然后将新的cache放入堆中,再调整堆满足条件。而hashMap中存储的是key和堆的节点的对应关系。

    这个方法AC了。

    稍微查了一下,有个更好的办法,即依然使用队列实现,但是队列用链表实现。

    然而用一个HashMap表征key和队列中节点的对应关系,这样可以保证快速找到队列中的节点。

     
     
  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/elnino/p/5607783.html
Copyright © 2011-2022 走看看