設(shè)計(jì)一個(gè)LRU

原文鏈接
一個(gè)更好的實(shí)現(xiàn)
作為演示代碼狗热,做了以下的簡(jiǎn)化處理:

  • 緩存結(jié)果是網(wǎng)絡(luò)查詢結(jié)果
  • 不對(duì)輸入進(jìn)行校驗(yàn)
  • 假設(shè)內(nèi)存能夠存放所有內(nèi)容
class Node(object):

    def __init__(self, results):
        self.results = results
        self.prev = None
        self.next = None


class LinkedList(object):

    def __init__(self):
        self.head = None
        self.tail = None

    def move_to_front(self, node):  # ...
    def append_to_front(self, node):  # ...
    def remove_from_tail(self):  # ...


class Cache(object):

    def __init__(self, MAX_SIZE):
        self.MAX_SIZE = MAX_SIZE
        self.size = 0
        self.lookup = {}  # key: query, value: node
        self.linked_list = LinkedList()

    def get(self, query)
        """Get the stored query result from the cache.
        
        Accessing a node updates its position to the front of the LRU list.
        """
        node = self.lookup.get(query)
        if node is None:
            return None
        self.linked_list.move_to_front(node)
        return node.results

    def set(self, results, query):
        """Set the result for the given query key in the cache.
        
        When updating an entry, updates its position to the front of the LRU list.
        If the entry is new and the cache is at capacity, removes the oldest entry
        before the new entry is added.
        """
        node = self.lookup.get(query)
        if node is not None:
            # Key exists in cache, update the value
            node.results = results
            self.linked_list.move_to_front(node)
        else:
            # Key does not exist in cache
            if self.size == self.MAX_SIZE:
                # Remove the oldest entry from the linked list and lookup
                self.lookup.pop(self.linked_list.tail.query, None)
                self.linked_list.remove_from_tail()
            else:
                self.size += 1
            # Add the new key and value
            new_node = Node(results)
            self.linked_list.append_to_front(new_node)
            self.lookup[query] = new_node

從數(shù)據(jù)結(jié)構(gòu)上來講,主要用到的是鏈表(比較好的方式其實(shí)是雙鏈表事期,有時(shí)會(huì)配合哈希表來提升查詢效率)。
下面是Leetcode上的題目參考解法:

class List(object):
    @staticmethod
    def delete(elem):
        elem.prev.next = elem.next
        elem.next.prev = elem.prev
        return elem
    
    @staticmethod   
    def move(elem, newPrev, newNext):
        elem.prev = newPrev
        elem.next = newNext
        newPrev.next = elem
        newNext.prev = elem
        
    @staticmethod
    def append(head, elem):
        List.move(elem, head.prev, head)
    
    @staticmethod
    def isEmpty(head):
        return head.next == head.prev == head
        
    @staticmethod
    def initHead(head):
        head.prev = head.next = head

class Node(object):
    def __init__(self, key, value, head):
        self.key = key
        self.value = value
        self.head = head
        self.prev = self.next = None
        
    def hit(self):
        List.delete(self)
        List.append(self.head, self)

class LRUCache(object):
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.d = {}
        self.cap = capacity
        self.head = Node(-1, -1, None)
        List.initHead(self.head)

    def get(self, key):
        """
        :rtype: int
        """
        if key not in self.d:
            return -1
        self.d[key].hit()
        return self.d[key].value
        

    def set(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: nothing
        """
        if self.cap == 0:
            return
        
        if key in self.d:
            self.d[key].hit()
            self.d[key].value = value
        else:
            if len(self.d) >= self.cap:
                oldNode = List.delete(self.head.next)
                del self.d[oldNode.key]
                
            newNode = Node(key, value, self.head)
            List.append(self.head, newNode)
            self.d[key] = newNode
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末朵纷,一起剝皮案震驚了整個(gè)濱河市传趾,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌负蚊,老刑警劉巖神妹,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異家妆,居然都是意外死亡鸵荠,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門伤极,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蛹找,“玉大人,你說我怎么就攤上這事哨坪∮辜玻” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵当编,是天一觀的道長(zhǎng)届慈。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么金顿? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任臊泌,我火速辦了婚禮,結(jié)果婚禮上揍拆,老公的妹妹穿的比我還像新娘渠概。我一直安慰自己,他們只是感情好嫂拴,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布高氮。 她就那樣靜靜地躺著,像睡著了一般顷牌。 火紅的嫁衣襯著肌膚如雪剪芍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天窟蓝,我揣著相機(jī)與錄音罪裹,去河邊找鬼。 笑死运挫,一個(gè)胖子當(dāng)著我的面吹牛状共,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播谁帕,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼峡继,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了匈挖?” 一聲冷哼從身側(cè)響起碾牌,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎儡循,沒想到半個(gè)月后舶吗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡择膝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年誓琼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肴捉。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腹侣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出齿穗,到底是詐尸還是另有隱情傲隶,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布缤灵,位于F島的核電站伦籍,受9級(jí)特大地震影響蓝晒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜帖鸦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一芝薇、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧作儿,春花似錦洛二、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至娶吞,卻和暖如春垒迂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背妒蛇。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工机断, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人绣夺。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓吏奸,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親陶耍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子奋蔚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 一、MySQL架構(gòu)與歷史 A.并發(fā)控制 1.共享鎖(shared lock烈钞,讀鎖):共享的泊碑,相互不阻塞的 2.排他...
    ZyBlog閱讀 19,837評(píng)論 3 177
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司棵磷,掛了不少蛾狗,但最終還是拿到小米、百度仪媒、阿里、京東谢鹊、新浪算吩、CVTE、樂視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,247評(píng)論 11 349
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,101評(píng)論 1 32
  • 針對(duì)項(xiàng)目中有的時(shí)候如果一個(gè)界面上有多個(gè)按鈕佃扼,然后這個(gè)時(shí)候如果同時(shí)按下兩個(gè)以上按鈕偎巢,那么這些按鈕按下效果都會(huì)出現(xiàn),以...
    紫金飛俠雷閱讀 745評(píng)論 0 2
  • 一兼耀、什么是指數(shù)基金 股票是股份制企業(yè)所有者擁有公司資產(chǎn)和權(quán)益的憑證压昼。上市的股票可在股票交易所自由買賣求冷,我們大部分人...
    虛室生白R(shí)io閱讀 1,531評(píng)論 4 6