LeetCode Hot100 刷题笔记(6)—— 栈、堆

目录

前言

一、栈

[1. 有效的括号](#1. 有效的括号)

[2. 最小栈](#2. 最小栈)

[3. 字符串解码](#3. 字符串解码)

[4. 每日温度](#4. 每日温度)

[5. 柱状图中最大的矩形](#5. 柱状图中最大的矩形)

二、堆

[1. 数组中的第K个最大元素](#1. 数组中的第K个最大元素)

[2. 前K个高频元素](#2. 前K个高频元素)

[3. 数据流中的中位数](#3. 数据流中的中位数)


前言

一、栈:有效的括号,最小栈,字符串解码,每日温度,柱状图中最大的矩形。

二、堆:数组中的第K个最大元素,前K个高频元素,数据流中的中位数。


一、

1. 有效的括号

原题链接:20. 有效的括号 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def isValid(self, s):
        dicts = {
            ')':'(',
            ']': '[',
            '}': '{'
        }
        stack = []
        for s_ in s:
            if stack and s_ in dicts:
                if stack[-1] == dicts[s_]: 
                    stack.pop()
                else:
                    return False
            else:
                stack.append(s_)
        return not stack

2. 最小栈

原题链接:155. 最小栈 - 力扣(LeetCode)

python 复制代码
class MinStack(object):
    def __init__(self):
        self.lst = []

    def push(self, val):
        self.lst.append(val)

    def pop(self):
        self.lst.pop()

    def top(self):
        return self.lst[-1]

    def getMin(self):
        return min(self.lst)
        
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

3. 字符串解码

原题链接:394. 字符串解码 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def decodeString(self, s):
        stack = []
        res, dig = '', 0
        for s_ in s:
            if s_.isdigit():
                dig = dig*10 + int(s_)   # 处理300, 21等数字
            elif 'a'<=s_<='z':
                res = res + s_
            elif s_ == '[':
                stack.append((res, dig))
                res, dig = '', 0
            else:
                res_top, dig_top = stack.pop()
                res = res_top + res * dig_top   # [('', 3), ('a', 0)] --> res = 'a' --> res = ''+ 'a'*3 = 'aaa'
        return res

4. 每日温度

原题链接:739. 每日温度 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def dailyTemperatures(self, temperatures):
        stack = []
        T = temperatures
        dicts = {i:0 for i in range(len(T))}

        for i in range(len(T)):
            while stack and T[stack[-1]] < T[i]:
                dicts[stack[-1]] = i - stack[-1]
                stack.pop()
            stack.append(i)
        return list(dicts.values())

5. 柱状图中最大的矩形

原题链接:84. 柱状图中最大的矩形 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def largestRectangleArea(self, heights):
        stack = []
        heights = [0] + heights + [0]
        res = 0
        n = len(heights)
        for i in range(n):
            while stack and heights[stack[-1]] > heights[i]:
                h=heights[stack.pop()]
                w = i-1-stack[-1]
                res = max(res, h*w)  # h递减,w递增
            stack.append(i)
        return res

二、

1. 数组中的第K个最大元素

原题链接:215. 数组中的第K个最大元素 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def findKthLargest(self, nums, k):
        nums.sort()
        nums.reverse()
        return nums[k-1]

2. 前K个高频元素

原题链接:347. 前 K 个高频元素 - 力扣(LeetCode)

python 复制代码
# 解法(1)
class Solution(object):
    def topKFrequent(self, nums, k):
        from collections import Counter
        lst = []
        for k, v in Counter(nums).most_common(k):
            lst.append(k)
        return lst

# 解法(2)
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        snums = set(nums)
        dicts = {k:0 for k in snums}
        for n in nums:
            if n in dicts:
                dicts[n]+=1
        dicts_sort = sorted(dicts.items(), key=lambda x: x[1], reverse=True)
        lst = []
        for k,v in dicts_sort[:k]:
            lst.append(k)
        return lst

3. 数据流中的中位数

原题链接:295. 数据流的中位数 - 力扣(LeetCode)

python 复制代码
class MedianFinder(object):
    def __init__(self):
        self.lst = [] 
    def addNum(self, num):
        self.lst.append(num)
    def findMedian(self):
        self.lst.sort()
        ln = len(self.lst)
        if ln % 2 == 0:
           mid = (self.lst[ln//2-1] + self.lst[ln//2]) / 2.0 
        else:
            mid = self.lst[ln//2]
        return mid
相关推荐
使一颗心免于哀伤11 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
_落纸2 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE2 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha2 天前
SpringBoot
笔记·学习
Hello_Embed3 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中3 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
Grassto3 天前
RAG 从入门到放弃?丐版 demo 实战笔记(go+python)
笔记
Magnetic_h3 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
周周记笔记3 天前
学习笔记:第一个Python程序
笔记·学习
丑小鸭是白天鹅3 天前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin