标签:style blog http io ar color os sp for
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
.
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!
Array Stack Two Pointers
1 #include <iostream> 2 #include <stack> 3 using namespace std; 4 5 class Solution { 6 public: 7 int trap(int A[], int n) { 8 if(n<3) return 0; 9 int curIdx = 0; 10 11 stack<int> stk; 12 13 int retSum = 0; 14 for(;curIdx<n;curIdx++){ 15 if(stk.empty()){ 16 stk.push(curIdx); 17 continue; 18 } 19 int stkTop = stk.top(); 20 if(A[stkTop]>=A[curIdx]){ 21 stk.push(curIdx); 22 continue; 23 } 24 while(!stk.empty()){ 25 int dit = stkTop; 26 stk.pop(); 27 if(stk.empty()) break; 28 stkTop =stk.top(); 29 retSum += (min(A[stkTop],A[curIdx])-A[dit])*(curIdx-stkTop - 1); 30 if(A[stkTop]>A[curIdx]) break; 31 } 32 stk.push(curIdx); 33 } 34 return retSum; 35 } 36 }; 37 38 int main() 39 { 40 int A[]= {0,1,0,2,1,0,1,3,2,1,2,1}; 41 Solution sol; 42 cout<<sol.trap(A,sizeof(A)/sizeof(int))<<endl; 43 return 0; 44 }
[LeetCode] Trapping Rain Water 栈
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4158426.html