• leetcode LRU Cache python


    class Node(object):
        def __init__(self,k,x):
            self.key=k
            self.val=x
            self.prev=None
            self.next=None
    class DoubleLinkedList(object):
        def __init__(self):
            self.tail=None
            self.head=None
        def isEmpty(self):
            return not self.None
        def removeLast(self):
            self.remove(self.tail)
        def remove(self,node):
            if self.head == self.tail:
                self.head,self.tail = None,None
                return
            if node == self.head:
                node.next.prev=None
                self.head=node.next
                return
            if node == self.tail:
                node.prev.next=None
                self.tail=node.prev
                return
            node.prev.next=node.next
            node.next.prev=node.prev
        def addFirst(self,node):
            if not self.head:
                self.head=self.tail=node
                node.prev=node.next=None
                return
            node.next=self.head
            self.head.prev=node
            self.head=node
            node.prev=None
        
    class LRUCache(object):
    
        def __init__(self, capacity):
            """
            :type capacity: int
            """
            self.capacity=capacity
            self.size=0
            self.p=dict()
            self.cache=DoubleLinkedList()
    
        def get(self, key):
            """
            :rtype: int
            """
            if (key in self.p) and self.p[key]:
                self.cache.remove(self.p[key])
                self.cache.addFirst(self.p[key])
                return self.p[key].val
            else:
                return -1
    
        def set(self, key, value):
            """
            :type key: int
            :type value: int
            :rtype: nothing
            """
            if key in self.p:
                self.cache.remove(self.p[key])
                self.cache.addFirst(self.p[key])
                self.p[key].val=value
            else:
                node=Node(key,value)
                self.p[key]=node
                self.cache.addFirst(node)
                self.size+=1
                if self.size > self.capacity:
                    self.size-=1
                    del self.p[self.cache.tail.key]
                    self.cache.removeLast()

     @link https://github.com/Linzertorte/LeetCode-in-Python/blob/master/LRUCache.py

  • 相关阅读:
    LA 3026 Period
    Touch
    Uva 11762 Race to 1
    清北学堂模拟赛d1t2 火柴棒 (stick)
    清北学堂模拟赛d1t1 位运算1(bit)
    常州模拟赛d8t2 绘画
    常州模拟赛d8t1 友好数对
    常州模拟赛d5t3 appoint
    常州模拟赛d7t1 亲戚
    常州模拟赛d7t3 水管
  • 原文地址:https://www.cnblogs.com/allenhaozi/p/5027790.html
Copyright © 2020-2023  润新知