一枚菜鸟的leetcode刷题笔记 - Day12

本文探讨了数据结构中的LRU缓存机制,通过Python实现了一个O(1)时间复杂度的LRUCache类。此外,还介绍了如何使用快慢指针对链表进行排序以及设计一个支持查找最大值和弹出最大值的最大栈,同样提供了Python实现。这些数据结构和算法在实际编程中有着广泛应用。
摘要由CSDN通过智能技术生成

146 - LRU 缓存机制

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。

实现 LRUCache 类:

  • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1。
  • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

进阶:你是否可以在 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])

  • key: 要删除的键值
  • default: 如果没有 key,返回 default 值
    返回被删除的值。

148 - 排序链表

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 排序链表

716 - 最大栈

设计一个最大栈数据结构,既支持栈操作,又支持查找栈中最大元素。

实现 MaxStack 类:

  • MaxStack() 初始化栈对象
  • void push(int x) 将元素 x 压入栈中。
  • int pop() 移除栈顶元素并返回这个元素。
  • int top() 返回栈顶元素,无需移除。
  • int peekMax() 检索并返回栈中最大元素,无需移除。
  • int popMax() 检索并返回栈中最大元素,并将其移除。如果有多个最大元素,只要移除最靠近栈顶的那个

底层为链表

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很难写。寻找最大值时,最好在栈的层面操作,分两个步骤:

  1. 逐次弹出栈顶元素,并用列表记录弹出的元素,直到弹出的元素值=当前max栈维护的最大值(max栈的最大值也需要弹出)
  2. 在按照顺序把列表中的元素压入栈,直接调用栈自身的push方法,因为该方法同时维护了max栈

底层为数组

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

以后遇到栈相关的问题还是用数组来写,比链表舒服多了,还更快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值