0
点赞
收藏
分享

微信扫一扫

LeetCode 接雨水 单调栈随便做做

题目链接:​​力扣​​

LeetCode 接雨水 单调栈随便做做_leetcode 

不得不说,LeetCode有的困难题还是过于简单,相比于CodeForces各个知识点杂合在一起考法来说,这种单一的知识点还是很水的。

10分钟写完代码,单调栈做法

#include
using namespace std;


int trap(vector& height) {
stack sta, val;

int arrayCount = height.size();
int answer = 0;
for(int i=0; i int cur = height[i];
int minValue = 0, length = 0;
while(sta.size() && sta.top() < cur){
int topValue = sta.top();
int curLen = val.top();
val.pop();
sta.pop();
answer = answer + (topValue - minValue) * length;
minValue = topValue;
length = length + curLen;
}
if(sta.size()){
answer = answer + (cur - minValue) * length;
}
// printf("curcur:%d answer:%d\n", cur, answer);
sta.push(cur);
val.push(length + 1);
}

return answer;

}

int main()
{
int n;
vectorG;
cin>>n;
for(int i=1;i<=n;++i){
int val;
cin>>val;
G.push_back(val);
}
printf("%d %d\n", trap(G), G.size());
}
/*

12
0 1 0 2 1 0 1 3 2 1 2 1


6
4 2 0 3 2 5
*/


举报

相关推荐

0 条评论