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
这个题的意思是计算可以盛水的多少,可以使用双指针,单次循环法,压栈方法。
1)
class Solution {
public int trap(int[] height) {
if(height == null && height.length == 0){
return 0;
}
int size = 0;
int max = 0;
int[] column = new int[height.length];
for(int i = 0 ; i < height.length; ++i){
column[i] = max;
max = Math.max(max,height[i]);
}
max = 0;
for(int i = height.length - 1 ; i >= 0; --i){
column[i] = Math.min(max,column[i]);
max = Math.max(max,height[i]);
size += column[i] > height[i] ? Math.abs(column[i] - height[i]) : 0;
}
return size;
}
}
2)双指针
class Solution {
public int trap(int[] A) {
int n = A.length;
int left = 0, right = n - 1;
int maxLeft = 0, maxRight = 0;
int ans = 0;
while (left < right) {
if (A[left] < A[right]) {
if (A[left] >= maxLeft) {
maxLeft = A[left];
} else {
ans += maxLeft - A[left];
}
left ++;
} else {
if (A[right] >= maxRight) {
maxRight = A[right];
} else {
ans += maxRight - A[right];
}
right --;
}
}
return ans;
}
}
3)
class Solution {
//11.20
public int trap(int[] height) {
Stack<Integer> st = new Stack();
int lastCounted = -1, lastCountedHeight, w,h;
int area = 0;
for (int i = 0; i< height.length; i++) {
int curHeight = height[i];
if (curHeight == 0)
continue;
while (!st.isEmpty()) {
int lastBlock = st.peek();
// System.out.format("===%d %d %d %d %d %d\n", i, area, lastBlock, height[lastBlock],curHeight,st.size());
if (height[lastBlock] > curHeight) {
w = i - lastBlock - 1;
h = curHeight;//as curHeihgt is smaller
lastCountedHeight = 0;
if (lastCounted > lastBlock)
lastCountedHeight = height[lastCounted];
lastCounted = i;
area = area+ (w * h) - (w * lastCountedHeight);
// System.out.format("%d %d %d %d %d %d\n", i, area, w, h, lastCountedHeight,st.size());
st.push(i);
break;
}
st.pop();
w = i - lastBlock - 1;
h = height[lastBlock];
lastCountedHeight = 0;
if (lastCounted > lastBlock)
lastCountedHeight = height[lastCounted];
lastCounted = lastBlock;
area = area + (w * h) - (w * lastCountedHeight);
//System.out.format("--%d %d %d %d %d %d\n", i, area, w, h, lastCountedHeight, st.size());
}
//System.out.println(i);
if (st.isEmpty()) {
st.push(i);
}
}
return area;
}
}
注意细节,两端的节点。