码迷,mamicode.com
首页 > 系统相关 > 详细

leetcode146 LRU Cache

时间:2020-03-06 22:05:50      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:complex   not found   aci   return   元素   函数   reac   sts   not   

 1 """
 2 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
 3 get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
 4 put(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.
 5 The cache is initialized with a positive capacity.
 6 Follow up:
 7 Could you do both operations in O(1) time complexity?
 8 Example:
 9 LRUCache cache = new LRUCache( 2 /* capacity */ );
10 cache.put(1, 1);
11 cache.put(2, 2);
12 cache.get(1);       // returns 1
13 cache.put(3, 3);    // evicts key 2
14 cache.get(2);       // returns -1 (not found)
15 cache.put(4, 4);    // evicts key 1
16 cache.get(1);       // returns -1 (not found)
17 cache.get(3);       // returns 3
18 cache.get(4);       // returns 4
19 """
20 """
21 用dict存储元素
22 用list存储dict里的key
23 用list里的insert函数和index函数pop函数来维护队列
24 保证能在队头加元素,删除任意index位置元素
25 """
26 class LRUCache:
27 
28     def __init__(self, capacity: int):
29         self.len = capacity
30         self.d = {}
31         self.l = []
32 
33     def get(self, key: int) -> int:
34         val = self.d.get(key)
35         if val and self.l[0] != key: #如果查找的值不在队头
36             index = self.l.index(key)
37             self.l.pop(index)
38             self.l.insert(0, key)
39         val = val if val else -1
40         return val
41 
42     def put(self, key: int, value: int) -> None:
43         if self.d.get(key): #如果重复
44             index = self.l.index(key)
45             self.d.pop(key)
46             self.l.pop(index)
47         if len(self.l) >= self.len: #如果队满
48             x = self.l.pop(-1)
49             self.d.pop(x)
50         self.d[key] = value
51         self.l.insert(0, key)

 

leetcode146 LRU Cache

标签:complex   not found   aci   return   元素   函数   reac   sts   not   

原文地址:https://www.cnblogs.com/yawenw/p/12430780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!