2018-10-23/24 LRU Cache [H]

  1. LRU Cache = LC: 146

Have Practiced: 0
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.

class LinkedNode:
    def __init__(self, key=None, value=None, next=None):
        self.key = key
        self.value = value
        self.next = next


class LRUCache:
    """
    @param: capacity: An integer
    """
    def __init__(self, capacity):
        self.hash = {}
        self.head = LinkedNode() # dummy
        self.tail = self.head
        self.capacity = capacity

    # change "head -> node1 -> node2"
    # to "head -> node1 -> node2 -> node3"
    def push_back(self, node):
        self.hash[node.key] = self.tail
        self.tail.next = node
        self.tail = node
    
    # change "head -> node1 -> node2 -> node3"
    # to "head -> node2 -> node3"
    def pop_front(self,):
        del self.hash[self.head.next.key] # delete a reference, not node
        self.hash[self.head.next.next.key] = self.head
        self.head.next = self.head.next.next
    
    # change "head -> node -> node2"
    # to "head -> node2 -> node"
    def move_to_back(self, prev):
        node = prev.next
        if node == self.tail:
            return
        prev.next = node.next
        self.hash[node.next.key] = prev
        node.next = None
        self.push_back(node)
    
    """
    @param: key: An integer
    @return: An integer
    """
    def get(self, key):
        if key in self.hash:
            self.move_to_back(self.hash[key])
            return self.hash[key].next.value
        return -1

    """
    @param: key: An integer
    @param: value: An integer
    @return: nothing
    """
    def set(self, key, value):
        if key in self.hash:
            self.move_to_back(self.hash[key])
            self.hash[key].next.value = value
        else:
            self.push_back(LinkedNode(key, value))
            if len(self.hash) > self.capacity:
                self.pop_front()

Time: O(1) for all
Space: ``

Notes:

  1. I need to understand WHAT is LRU cache:
    Least Recently Used - The data you visited in the last round, you will very probably visit it in the next round.
  2. Use linked list in this problem, because I want to have pop_front(), push_back() and move_to_back().
    • Linked list takes least time, O(1), but not for move_to_back(). Therefore, use hash map(cache key, linked list node) to look up nodes in O(1) time
    • If I need to remove a node, I need to know its prev node. Therefore, Doubly linked list is needed. Or, use hash map(cache key, prev node) instead. Hash map works 1) adding another property of linked, prev. 2) easy to edit value of node.
  3. Learn to write LinkedNode() in Python.
    Remember to initialize all values to be None
def __init__(self, key=None, value=None, next=None):
  1. Relate this problem to First Unique Character in a String. A follow-up of this problem is data stream.

Extension:

  1. Python Tricks, use OrderedDict which has the same concept. Similar to LinkedHashMap in Java.
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache:
            return -1
        value = self.cache.pop(key) # take it out
        self.cache[key] = value # insert it back
        return value
        
    def set(self, key, value):
        if key in self.cache:
            self.cache.pop(key)
        elif len(self.cache) == self.capacity:
            ## last = True => FILO
            ## last = False => FIFO
            self.cache.popitem(last = False) # just pop head or tail, no key input
        self.cache[key] = value
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,324评论 0 10
  • 4/16加入的初心: 1.微商營銷太酷了,我要好好學微營銷 ! 2.一手江山一手心肝️️❤️❤️ 其实我很早就开始...
    沛沛小詩阅读 594评论 0 1
  • 1、工作继续跟wms做对接,顺便讨论和准备和AGV的对接。对于小公司,需要把握的一点是,那些事情你要全力向前冲,保...
    吕鹏_hunhun阅读 191评论 1 0
  • 想问世间的风雨 每一次都是为谁 还有划过天际的闪电 是为相遇 还是道别 不断旋转的年轮 留不住秋华春泥 我静守空...
    伏笔_ac61阅读 108评论 0 0
  • 2018年跟着亭主,开始关注财富、财务这块。 新年阅读的第一本有关金钱的书,就是《小狗钱钱》的作者博多.舍费尔写的...
    咏儿正向教养力阅读 602评论 2 4