[LeetCode] Trapping Rain Water 栈

时间:2024-08-05 23:34:56

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

[LeetCode] Trapping Rain Water 栈

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Hide Tags

Array Stack Two Pointers

 

     好开心,逻辑这么麻烦的题目,写了一次没有错,提交了直接过。
     做了前面题目可能容易想,假如用一个stack 维护下标,其对应的数列 是非升序的,后面的工作中就维护这一个stack。在一个非降序的stack,如果考虑的值比top 小,则加入stack。如果大于top 值,则弹出小于的值,计算return 值。
     例如遍历到idx =5时候,stack 里面的 下标有:  3,4
  a[5]<a[4],所以加入stack,然后遍历到idx =6时候,stack为:3,4,5
  那么弹出 stack 的top,然后计算弹出值水坑,这时候只需要计算红色的部分,通过stack 弹出后的top=4,坑=5,和墙=6,的时候更新,
[LeetCode] Trapping Rain Water 栈
  然后更新stack 变成:3,4,6,接着便是遍历idx =7,这时候弹出的是6,通过top=4,坑6,墙=7 计算,这个值为0.
  因为stack 的top 还是小于,所以继续弹出,然后计算,top=3,坑4,墙7,计算了下图的部分:
[LeetCode] Trapping Rain Water 栈
 此时stack: 3,继续弹出,但此时stack 没有top 了,所以可以结束这一步,将idx=7 压入stack。
代码:
 #include <iostream>
#include <stack>
using namespace std; class Solution {
public:
int trap(int A[], int n) {
if(n<) return ;
int curIdx = ; stack<int> stk; int retSum = ;
for(;curIdx<n;curIdx++){
if(stk.empty()){
stk.push(curIdx);
continue;
}
int stkTop = stk.top();
if(A[stkTop]>=A[curIdx]){
stk.push(curIdx);
continue;
}
while(!stk.empty()){
int dit = stkTop;
stk.pop();
if(stk.empty()) break;
stkTop =stk.top();
retSum += (min(A[stkTop],A[curIdx])-A[dit])*(curIdx-stkTop - );
if(A[stkTop]>A[curIdx]) break;
}
stk.push(curIdx);
}
return retSum;
}
}; int main()
{
int A[]= {,,,,,,,,,,,};
Solution sol;
cout<<sol.trap(A,sizeof(A)/sizeof(int))<<endl;
return ;
}