[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
View Code
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
相关文章推荐
- [LeetCode] Trapping rain water
- leetcode编程记录17 #42 Trapping Rain Water
- Leetcode 42 Trapping Rain Water
- Leetcode Trapping Rain Water
- Leetcode206: Trapping Rain Water
- LeetCode 042 Trapping Rain Water
- LeetCode: Trapping Rain Water
- [leetcode] Trapping Rain Water
- [leetcode]Trapping Rain Water
- LeetCode Trapping Rain Water等雨水的凹槽容量
- Trapping Rain Water[leetcode]
- leetcode42_Trapping Rain Water
- LeetCode - Trapping Rain Water 等雨水的凹槽容量
- [LeetCode] Trapping Rain Water 收集雨水
- leetcode---trapping-rain-water
- LEETCODE: Trapping Rain Water
- LeetCode (42): Trapping Rain Water
- LeetCode - Trapping Rain Water
- leetcode - Trapping Rain Water
- [LeetCode] Trapping Rain Water