您的位置:首页 > 移动开发

[LeetCode] Trapping Rain Water 栈

2014-12-11 20:22 381 查看
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
.

#include <iostream>
#include <stack>
using namespace std;

class Solution {
public:
int trap(int A[], int n) {
if(n<3) return 0;
int curIdx = 0;

stack<int> stk;

int retSum = 0;
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 - 1);
if(A[stkTop]>A[curIdx]) break;
}
stk.push(curIdx);
}
return retSum;
}
};

int main()
{
int A[]= {0,1,0,2,1,0,1,3,2,1,2,1};
Solution sol;
cout<<sol.trap(A,sizeof(A)/sizeof(int))<<endl;
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: