问题描述
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.
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
解题思路
解法一
根据题意和实例,我第一个想到的解决方法是通过栈的方式实现,先找到这个数组的最大值的下标。从下标0遍历到最大值下标,通过栈操作计算出前半段的积水。从最大下标到n-1, 和前半段计算方式相同。
public int trap(int[] height) {
if(height.length == 0 || height.length == 1 || height.length == 2) {
return 0;
}
int result = 0;
// 寻找最大值下标
int index = 0, max = height[0];
for(int i = 1; i < height.length; i++ ) {
if(height[i] > max) {
index = i;
max = height[i];
}
}
Stack<Integer> stack = new Stack<Integer>();
// 除去数组开头连续为0的项
int n = 0 ;
while(height[n] == 0){
n++;
}
stack.push(height[n]);
int left = height[n];
int start = n;
for(int i = n + 1; i <= index; i++ ) {
if(height[i] < left) {
stack.push(height[i]);
}else if(height[i] >= left){
int s = 0;
while(!stack.empty()) {
s += stack.pop();
}
// 计算积水
result += (i - start) * left - s;
stack.push(height[i]);
left = height[i];
start = i;
}
}
// 计算后半段
stack.clear();
// 除去数组末尾连续为0
int m = height.length - 1;
while(height[m] == 0){
m--;
}
stack.push(height[m]);
left = height[m];
start = m;
for(int j = m - 1; j >= index; j--) {
if(height[j] < left) {
stack.push(height[j]);
}else if(height[j] >= left){
int s = 0;
while(!stack.empty()) {
s += stack.pop();
}
// 计算积水
result += (start - j) * left - s;
stack.push(height[j]);
left = height[j];
start = j;
}
}
return result;
}
在LeetCode执行为4ms
解法二
第二种方法不太容易理解,但是解题思想很巧妙,通过双指针逼夹的方式。结合上面图比较容易理解。
public int trap(int[] A) {
int a=0;
int b=A.length-1;
int max=0;
int leftmax=0;
int rightmax=0;
while(a<=b){
leftmax=Math.max(leftmax,A[a]);
rightmax=Math.max(rightmax,A[b]);
if(leftmax<rightmax){
max+=(leftmax-A[a]);
a++;
}
else{
max+=(rightmax-A[b]);
b--;
}
}
return max;
}
在LeetCode执行时间为2ms