146.LRU缓存机制
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {}
def get(self, key: int) -> int:
# 搜索不到返回-1
if key not in self.cache:
return -1
# 取出缓存中的key并赋值
self.cache[key] = self.cache.pop(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
# 如存在就先删除key
if key in self.cache:
self.cache.pop(key)
self.cache[key] = value
# 取缓存列表中最先进入的key
if len(self.cache) > self.capacity:
x = list(self.cache)[0]
self.cache.pop(x)
148.排序链表
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
mid=self.findmid(head)
left=head
right=mid.next
mid.next=None
l=self.sortList(left)
r=self.sortList(right)
return self.merge(l,r)
def findmid(self,head):
slow=head
fast=head
while fast.next and fast.next.next:
slow=slow.next
fast=fast.next.next
return slow
def merge(self,l,r):
dummy=ListNode(None)
cur=dummy
while l and r:
if l.val<=r.val:
cur.next=l
l=l.next
else:
cur.next=r
r=r.next
cur=cur.next
cur.next=l or r
return dummy.next
155.最小栈
class MinStack:
def __init__(self):
self._list = []
def push(self, x: int) -> None:
self._list.append(x)
self._min = min(self._list)
def pop(self) -> None:
self._list.pop()
self._min = not self._list or min(self._list)
def top(self) -> int:
return self._list[-1]
def getMin(self) -> int:
return self._min