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.
思路同在直方图中找最大矩形。维护一个递减的栈s,如果A[i]大于s.top(),一直出栈直A[i]<s.top()或者栈空。注意的是算面积时,每次出栈相当于把下面的坑填平。
AC代码:
class Solution { public: int trap(int A[], int n) { stack<int> s; int sum = 0; int base = A[0]; //记录栈底的值 for(int i = 0; i < n; ++i){ if(s.empty() || A[i] < A[s.top()]){ s.push(i); }else{ int maxVal = A[i]; if(A[i] > base){ //确定边界值 maxVal = base; base = A[i]; } while(!s.empty() && A[i] > A[s.top()]){ int tempVal = A[s.top()]; int tempIndex = s.top(); s.pop(); if(tempVal == maxVal){ //如果栈要空了,那么最后一个元素当成边界使用 break; } sum += (maxVal - tempVal) * (tempIndex - s.top()); } s.push(i); } } return sum; } };
浙公网安备 33010602011771号