from queue import Queue
import time
classLRUCache:def__init__(self, capacity:int):
self.size = capacity
self.box ={}
self.q = Queue()defget(self, key:int)->int:try:
now = time.time()
value = self.box[key][1]
self.box[key]=(now, value)
self.q.put((now, key))return value
except KeyError:return-1defput(self, key:int, value:int)->None:
now = time.time()
self.q.put((now, key))
self.box[key]=(now, value)iflen(self.box)> self.size:whileTrue:
mid = self.q.get()if self.box[mid[1]][0]== mid[0]:del self.box[mid[1]]break# Your LRUCache object will be instantiated and called as such:# obj = LRUCache(capacity)# param_1 = obj.get(key)# obj.put(key,value)
LeetCode148题: 排序链表
先遍历链表将其值存到列表中
对列表排序
写回即可
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defsortList(self, head: ListNode)-> ListNode:if head ==None:returnNonelist=[]
p = head
while p !=None:list.append(p.val)
p = p.nextlist.sort()
i =0
p = head
length =len(list)while i < length:
p.val =list[i]
p = p.next
i +=1return head
LeetCode第155题: 最小栈
在每次遍历压站和弹栈操作后更新最小值即可
classMinStack:def__init__(self):"""
initialize your data structure here.
"""
self.stack =[]
self.min=float('-inf')defpush(self, x:int)->None:
self.stack.append(x)
self.min=min(self.stack)defpop(self)->None:
resutl = self.stack.pop()iflen(self.stack)==0:return resutl
self.min=min(self.stack)return resutl
deftop(self)->int:return self.stack[len(self.stack)-1]defgetMin(self)->int:iflen(self.stack)<=0:returnNonereturn self.min# Your MinStack object will be instantiated and called as such:# obj = MinStack()# obj.push(x)# obj.pop()# param_3 = obj.top()# param_4 = obj.getMin()