运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。
实现 LRUCache 类:
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.LRUdict = {} #用于存储key-value对,但无顺序
self.LRUkey = [] #用于存储key,有顺序
def get(self, key: int) -> int:
if key in self.LRUdict:
#每次调用要把被调用的key移到最前
self.LRUkey.remove(key)
self.LRUkey.append(key)
return self.LRUdict[key]
return -1
def put(self, key: int, value: int) -> None:
if key in self.LRUdict:
self.LRUkey.remove(key)
self.LRUdict.pop(key)
elif len(self.LRUkey) == self.capacity:
self.LRUdict.pop(self.LRUkey[0]) #必须先弹出字典的key-value对,再弹出列表里的key值
self.LRUkey.pop(0)
self.LRUkey.append(key)
self.LRUdict[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。 ——from LRU缓存机制(包含流程图分析以及各操作的解析详解)
本解法完全参考了146 LRU缓存机制
利用python字典 + 列表的方式,字典用于存储key-value对,但没有顺序,因此需要一个列表用于记录顺序。
对于get函数,不止要返回字典的value,还要把get到的key的顺序调整到最前。
python字典的pop方法:
pop(key[,default])
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def sort(head, tail):
if not head:
return head
elif head.next == tail:
head.next = None
return head
fast, slow = head, head
while fast != tail:
fast, slow = fast.next, slow.next
if fast != tail:
fast = fast.next
mid = slow
return merge(sort(head, mid), sort(mid, tail))
def merge(head1, head2):
dummyHead = ListNode()
temp, temp1, temp2 = dummyHead, head1, head2
while temp1 and temp2:
if temp1.val < temp2.val:
temp.next = temp1
temp, temp1 = temp.next, temp1.next
else:
temp.next = temp2
temp, temp2 = temp.next, temp2.next
if temp1:
temp.next = temp1
else:
temp.next = temp2
return dummyHead.next
return sort(head, None)
这道题目综合了快慢指针二分链表 & 合并两个排序链表。
参考官方解答 & 「手画图解」归并排序 | 148 排序链表
设计一个最大栈数据结构,既支持栈操作,又支持查找栈中最大元素。
实现 MaxStack 类:
class linkedNode:
def __init__(self,x):
self.val = x
self.next = None
class basicStack:
def __init__(self,z):
self.head = linkedNode(z)
def basicpush(self, y):
nownode = linkedNode(y)
if not self.head.next:
self.head.next = nownode
else:
nownode.next = self.head.next
self.head.next = nownode
def basicpop(self):
if not self.head.next:
print('The Stack is Empty')
else:
tmp = self.head.next.val
self.head.next = self.head.next.next
return tmp
def basictop(self):
if not self.head.next:
print('The Stack is Empty')
return self.head.val
else:
return self.head.next.val
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.item = basicStack(None)
self.maxvalue = basicStack(float('-inf'))
def push(self, x: int) -> None:
self.item.basicpush(x)
if x >= self.maxvalue.basictop():
self.maxvalue.basicpush(x)
def pop(self) -> int:
if self.item.basictop() == self.maxvalue.basictop():
self.maxvalue.basicpop()
return self.item.basicpop()
def top(self) -> int:
return self.item.basictop()
def peekMax(self) -> int:
return self.maxvalue.basictop()
def popMax(self) -> int:
poplist = []
nowmax = self.maxvalue.basicpop()
while self.item.head.next:
popvalue = self.item.basicpop()
if popvalue == nowmax:
break
poplist.append(popvalue)
while poplist:
self.push(poplist.pop())
return nowmax
这一题其实是上面一题的升级版:多了一个弹出最大值的操作。弹出最大值破坏了max栈的结构,因为对于[5,1]这种栈,弹出5后,max栈没有值了。本解法底层用了链表来表示栈,如果在链表层面通过操作链表节点的val和next很难写。寻找最大值时,最好在栈的层面操作,分两个步骤:
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.item = []
self.maxval = [float('-inf')]
def push(self, x: int) -> None:
self.item.append(x)
if x >= self.maxval[-1]:
self.maxval.append(x)
def pop(self) -> int:
popval = self.item.pop()
if popval == self.maxval[-1]:
self.maxval.pop()
return popval
def top(self) -> int:
return self.item[-1]
def peekMax(self) -> int:
return self.maxval[-1]
def popMax(self) -> int:
curmax = self.maxval.pop()
poplist = []
while self.item:
popvalue = self.item.pop()
if popvalue == curmax:
break
poplist.append(popvalue)
while poplist:
self.push(poplist.pop())
return curmax
以后遇到栈相关的问题还是用数组来写,比链表舒服多了,还更快。