代码随想录算法训练营第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;
    }
};

总结

相关推荐
米粒13 分钟前
力扣算法刷题 Day 8
算法·leetcode·职场和发展
Sakinol#9 分钟前
Leetcode Hot 100 —— 普通数组
算法·leetcode
@Mike@17 分钟前
【算法】高精度
算法
leo__52018 分钟前
MHT多假设跟踪算法(Multiple Hypothesis Tracking)MATLAB实现
开发语言·算法·matlab
ShineWinsu18 分钟前
对于C++中unordered_set的详细介绍
数据结构·c++·算法·面试·stl·哈希表·unordered_set
吃着火锅x唱着歌19 分钟前
LeetCode 456.132模式
数据结构·算法·leetcode
二木九森21 分钟前
LeetCode-寻找环形链表的入口
算法·leetcode·链表
飞Link28 分钟前
耳机连接电脑时调节耳机音量电脑音量也会随着改变
算法·电脑
此方ls35 分钟前
机器学习聚类算法一——K均值
算法·机器学习·聚类
再难也得平35 分钟前
力扣73. 矩阵置零(Java解法)
算法·leetcode·矩阵