leetcode 42 单调栈解法
Problem: 42. 接雨水
思路
作为自己独立完成的第一道困难题,我觉得有必要纪念一下。就是单调栈的思路,不过需要减去栈中的每一项才是雨水的体积。最后一个因为不是柱子,所以在结束循环时可能会出现栈未空的情况,需要倒着再考虑一遍。
解题方法
遇到比当前大的就改变low,然后计算雨水含量,否则就入栈,栈未空时倒着再考虑一遍
复杂度
时间复杂度:
添加时间复杂度, 示例:
空间复杂度:
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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?