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

总结

相关推荐
2401_832131958 分钟前
模板编译期机器学习
开发语言·c++·算法
嵌入小生0079 分钟前
Data Structure Learning: Starting with C Language Singly Linked List
c语言·开发语言·数据结构·算法·嵌入式软件
ValhallaCoder12 分钟前
hot100-子串
数据结构·python·算法
ygklwyf15 分钟前
无向图的连通性之割点/边,点/边双连通分量
算法·无向图·圆方树
2401_8384725115 分钟前
单元测试在C++项目中的实践
开发语言·c++·算法
naruto_lnq21 分钟前
移动语义与完美转发详解
开发语言·c++·算法
MicroTech202531 分钟前
自适生长的点云智能:MLGO微算法科技基于双阈值与DDM的仿生式配准算法
科技·算法
yunsr39 分钟前
python作业1
开发语言·python·算法
清铎1 小时前
项目_华为杯’数模研赛复盘_第二问
深度学习·算法·机器学习
v_for_van1 小时前
力扣刷题记录1(无算法背景,纯C语言)
算法·leetcode·职场和发展