代码随想录第五十五天打卡

42. 接雨水

接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。

建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。

在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。

代码随想录

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

总结

把左边最大和右边最大就是要求面积的思路理清楚了其实后面实现就不难了。

84.  柱状图中最大的矩形

有了之前单调栈的铺垫,这道题目就不难了。

ongjiez代码随想录

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int>st;
        heights.insert(heights.begin(), 0); // 数组头部加入元素0
        heights.push_back(0); // 数组尾部加入元素0
        st.push(0);
        int res=0;
        for (int i=1;i<heights.size();i++){
            if (st.empty() || heights[st.top()]<heights[i])st.push(i);
            else{
                while (!st.empty() && heights[st.top()]>heights[i]){
                    int mid=st.top();
                    st.pop();
                    if (!st.empty())res=max(res,heights[mid]*(i-st.top()-1));
                    else res=max(res,heights[mid]*i);
                }
                st.push(i);
            }
        }
        return res;
    }
};

总结

我还在想怎么把栈剩余的元素给算上,原来在后面加上个0就可以了。

相关推荐

  1. 代码随想

    2024-07-14 07:24:04       25 阅读
  2. 代码随想第二

    2024-07-14 07:24:04       21 阅读
  3. 代码随想

    2024-07-14 07:24:04       28 阅读
  4. 代码随想

    2024-07-14 07:24:04       28 阅读
  5. 代码随想-刷题

    2024-07-14 07:24:04       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 07:24:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 07:24:04       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 07:24:04       58 阅读
  4. Python语言-面向对象

    2024-07-14 07:24:04       69 阅读

热门阅读

  1. 《HarmonyOS应用开发者基础认证》考试题目

    2024-07-14 07:24:04       27 阅读
  2. 每天一个数据分析题(四百二十六)- 总体方差

    2024-07-14 07:24:04       24 阅读
  3. [C++]类与对象

    2024-07-14 07:24:04       20 阅读
  4. 大模型日报 2024-07-13

    2024-07-14 07:24:04       20 阅读
  5. 家校管理系统

    2024-07-14 07:24:04       18 阅读
  6. 使用vllIm部署大语言模型

    2024-07-14 07:24:04       23 阅读
  7. 在Debian 7上安装和保护phpMyAdmin的方法

    2024-07-14 07:24:04       30 阅读
  8. Nginx 负载均衡详解

    2024-07-14 07:24:04       21 阅读
  9. Git常用命令

    2024-07-14 07:24:04       27 阅读
  10. 软设之访问者模式

    2024-07-14 07:24:04       19 阅读