zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):146-LRU Cache

    题目来源:

      https://leetcode.com/problems/lru-cache/


    实现一个LRU缓存。直接上代码。


    代码(python):

     1 class LRUCache(object):
     2 
     3     def __init__(self, capacity):
     4         """
     5         :type capacity: int
     6         """
     7         LRUCache.capacity = capacity
     8         LRUCache.length = 0
     9         LRUCache.dict = collections.OrderedDict()
    10 
    11     def get(self, key):
    12         """
    13         :rtype: int
    14         """
    15         try:
    16             value = LRUCache.dict[key]
    17             del LRUCache.dict[key]
    18             LRUCache.dict[key] = value
    19             return value
    20         except:
    21             return -1
    22 
    23     def set(self, key, value):
    24         """
    25         :type key: int
    26         :type value: int
    27         :rtype: nothing
    28         """
    29         try:
    30             del LRUCache.dict[key]
    31             LRUCache.dict[key] = value
    32         except:
    33             if LRUCache.length == LRUCache.capacity:
    34                 LRUCache.dict.popitem(last = False)
    35                 LRUCache.length -= 1
    36             LRUCache.dict[key] = value
    37             LRUCache.length += 1
    38         
    View Code
  • 相关阅读:
    省队集训Ⅱ-Day5
    省队集训Ⅱ-Day4
    省队集训Ⅱ-Day3
    省队集训Ⅱ-Day2
    省队集训Ⅱ-Day1
    并查集 Pro
    树上带修: 莫队Ⅳ
    树上骗分: 莫队Ⅲ
    带修骗分: 莫队Ⅱ
    骗分带师: 莫队Ⅰ
  • 原文地址:https://www.cnblogs.com/chruny/p/5477982.html
Copyright © 2011-2022 走看看