[LeetCode] Trapping Rain Water 栈
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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。