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
相关推荐
lil44x_8 分钟前
嵌入式学习笔记DAY23(树,哈希表)
笔记·学习
霸王蟹18 分钟前
常见面试题:Webpack的构建流程简单说一下。
前端·笔记·学习·webpack·node.js·vue
珊瑚里的鱼1 小时前
【滑动窗口】LeetCode 1004题解 | 最大连续1的个数 Ⅲ
开发语言·c++·笔记·算法·leetcode
大筒木老辈子2 小时前
Linux笔记---内核态与用户态
linux·运维·笔记
Vizio<2 小时前
基于MNIST数据集的手写数字识别(CNN)
人工智能·笔记·深度学习·神经网络·cnn
FBI HackerHarry浩3 小时前
Linux云计算训练营笔记day11(Linux CentOS7)
linux·运维·笔记·云计算
再看扣你眼3 小时前
系统安全及应用学习笔记
笔记·学习·系统安全
xuanshang_yutou3 小时前
调研函模板可参考,以无人机职业技能调研为例
笔记
再看扣你眼3 小时前
系统安全及应用深度笔记
linux·运维·笔记·安全·系统安全
安安csdn3 小时前
系统架构设计师考前冲刺笔记-第1章-系统工程与信息系统基础
笔记·系统架构