Leetcode: 42. Trapping Rain Water
求下雨后,给定的地形上积水最大的容积。有点接近与面试会问的提醒。
Stack解法
首先,积水的地方肯定是两边高中间低的地方。所以目标是找到递减序列后的递增序列,那么这两个序列中间必定会积水。需要把递减序列的高度和容积用stack存起来。
class Solution {
public:
int trap(int A[], int n) {
if(n<3) return 0;
stack<int> s;
s.push(0);
int water = 0;
for(int i=1; i<n; i++) {
if(A[i]>A[s.top()]) {
int bottom = A[s.top()];
s.pop();
while(!s.empty() && A[i]>=A[s.top()]) {
water += (A[s.top()]-bottom)*(i-s.top()-1);
bottom = A[s.top()];
s.pop();
}
if(!s.empty()) water += (A[i]-bottom)*(i-s.top()-1);
}
s.push(i);
}
return water;
}
};
two pointers解法
使用两个指针,对于对任意位置i,在i上的积水,由左右两边最高的bar:A[left] = max{A[j], j<i}, A[right] = max{A[j], j>i}
决定。定义Hmin = min(A[left], A[right])
,则积水量Si为:
Hmin <= A[i]
时,Si = 0
Hmin > A[i]
时,Si = Hmin - A[i]
class Solution {
public:
int trap(int A[], int n) {
if(n<3) return 0;
vector<int> leftHeight(n,0);
vector<int> rightHeight(n,0);
int water = 0;
for(int i=1; i<n; i++)
leftHeight[i] = max(leftHeight[i-1], A[i-1]);
for(int i=n-2; i>=0; i--) {
rightHeight[i] = max(rightHeight[i+1], A[i+1]);
int minHeight = min(leftHeight[i], rightHeight[i]);
if(minHeight>A[i]) water += (minHeight - A[i]);
}
return water;
}
};