2021-01-24

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值