问题描述:
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.
分析:我的解题思路是和图中的所示面积是相吻合的。这里面维护一个堆栈,如果当前元素大于栈顶元素,出栈,并在两个元素中维护一个面积数组。然后再进行完之后,处理一下余下的堆栈数据。然后再计算面积之和。
代码如下:344ms
public class Solution {
public int trap(int[] height) {
Stack<Integer> heightStack = new Stack<>();
List<Integer> indexList = new LinkedList<>();
int length = height.length;
int[] area = new int[length];
for(int i = 0;i<length;i++){
if(heightStack.isEmpty()){
heightStack.push(height[i]);
indexList.add(i);
continue;
}
int val = height[i];
while(!heightStack.isEmpty()){
int prev = heightStack.peek();
if(val<prev)
break;
int prevIndex = indexList.remove(indexList.size() - 1);
for(int j = prevIndex+1;j<i;j++){
area[j] = prev-height[j];
}
heightStack.pop();
}
heightStack.push(val);
indexList.add(i);
}
int head;
int headIndex;
while(!heightStack.isEmpty()){
head = heightStack.pop();
headIndex = indexList.remove(indexList.size()-1);
if(heightStack.isEmpty())
break;
int peekIndex = indexList.get(indexList.size()-1);
for(int i = headIndex-1;i>peekIndex;i--){
area[i] = head-height[i];
}
}
int count = 0;
for(int i = 0;i<length;i++) {
count += area[i];
}
return count;
}
}