leetcode 42 单调栈解法

Problem: 42. 接雨水

思路

作为自己独立完成的第一道困难题,我觉得有必要纪念一下。就是单调栈的思路,不过需要减去栈中的每一项才是雨水的体积。最后一个因为不是柱子,所以在结束循环时可能会出现栈未空的情况,需要倒着再考虑一遍。

解题方法

遇到比当前大的就改变low,然后计算雨水含量,否则就入栈,栈未空时倒着再考虑一遍

复杂度

时间复杂度:

添加时间复杂度, 示例: <O(3n)

空间复杂度:

O(n)

Code

class Solution {
public:
int trap(vector<int>& height) {
stack<int> temp;
int n=height.size();
int low=0,fast=1,ans=0;
if(n<=1) return 0;
while (fast<n)
{
if(height[fast]<height[low]){
temp.push(height[fast]);
fast++;
}
else{
int s=temp.size();
int tempheight=s*height[low];
while (!temp.empty())
{
int a=temp.top();
temp.pop();
tempheight-=a;
}
ans+=tempheight;
low=fast;
fast++;
}
}
if(!temp.empty()){
int a=0,count=0,tempheight=0;
bool judge=false;
while (!temp.empty())
{
if(temp.top()>=a) {
ans=ans+tempheight+a*count;
count=0;
tempheight=0;
a=temp.top();
}
else {count++;tempheight-=temp.top();}
temp.pop();
if(temp.size()==0&&judge==false) {temp.push(height[low]);judge=true;}//这里因为栈前面是有高柱子的,所以要把low按进去再考虑一遍
}
}
return ans;
}
};
posted @   oxidationreaction  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示