代码随想录算法训练营第44天 | 第十章 单调栈part02

文章目录


今日记录


42. 接雨水

Leetcode链接

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> st;
        st.push(0);
        int sum = 0;
        for (int i = 1; i < height.size(); i++) {
            if (height[i] < height[st.top()]) {
                st.push(i);
            } else if (height[i] == height[st.top()]) {
                st.pop();
                st.push(i);
            } else {
                while (!st.empty() && height[i] > height[st.top()]) {
                    int mid = st.top();
                    st.pop();
                    if (!st.empty()) {
                        int h = min(height[st.top()], height[i]) - height[mid];
                        int w = i - st.top() - 1;
                        sum += h * w;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
};

84.柱状图中最大的矩形

cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int result = 0;
        stack<int> st;
        st.push(0);
        heights.insert(heights.begin(), 0);
        heights.push_back(0);

        for (int i = 1; i < heights.size(); i++) {
            if (heights[i] > heights[st.top()]) {
                st.push(i);
            } else if (heights[i] == heights[st.top()]) {
                st.pop();
                st.push(i);
            } else {
                while (!st.empty() && heights[i] < heights[st.top()]) {
                    int mid = st.top();
                    st.pop();
                    int left = st.top();
                    int right = i;
                    int w = right - left - 1;
                    int h = heights[mid];
                    result = max(result, w * h);
                }
            }
            st.push(i);
        }
        return result;
    }
};

总结

相关推荐
刘永鑫Adam4 分钟前
BiB | 蒋超实验室开发 Kun-peng(鲲鹏):实现可扩展且准确的泛域宏基因组分类
人工智能·算法·机器学习·分类·数据挖掘
ltl9 分钟前
SM3 vs SHA-256:两个哈希函数的设计哲学与性能实测
后端·算法
知星小度S14 分钟前
算法训练之递归(一)
数据结构·算法
未来之窗软件服务19 分钟前
SenseVoicecpp ggml-webgpu大模型[AI人工智能(七十五)]—东方仙盟
c++·人工智能·算法·仙盟创梦ide·东方仙盟
ZPC821032 分钟前
ROS 2 手眼标定完整方案
人工智能·算法·性能优化·机器人
Q741_1471 小时前
每日一题 力扣 3418. 机器人可以获得的最大金币数 力扣 215. 数组中的第K个最大元素 动态规划 TopK问题 C++ 题解
c++·算法·leetcode·动态规划·topk
Frostnova丶1 小时前
LeetCode 3418.机器人可以获得的最大金币数
算法·leetcode
寻寻觅觅☆1 小时前
东华OJ-基础题-31-素数(C++)
开发语言·c++·算法
仟濹1 小时前
【算法打卡day36(2026-04-02 周四)】DFS专项训练3
算法·深度优先
B1acktion1 小时前
2.3.插入排序——像打牌一样整理数组,为什么它对“几乎有序”数据特别友好?
数据结构·算法·排序算法