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. Thanks Marcos for contributing this image!
解决思路
假设数组的长度为len,(1) 找到最高的那个柱子highest;
(2) 双指针:从0到highest, 从len-1到highest;
(3) 辅助栈s:存的是柱子高度的升序序列,如果遇到比栈顶元素小的高度,则能够储存水量为s.peek()-cur
时间空间复杂度均为O(n).
程序
public class Solution { public int trap(int[] height) { if (height == null || height.length == 0) { return 0; } int highest = getHighestIdx(height); int water = 0; Stack<Integer> s = new Stack<Integer>(); for (int i = 0; i < highest; i++) { if (s.isEmpty() || height[i] > s.peek()) { s.push(height[i]); } else { water += s.peek() - height[i]; } } s = new Stack<Integer>(); for (int i = height.length - 1; i > highest; i--) { if (s.isEmpty() || height[i] > s.peek()) { s.push(height[i]); } else { water += s.peek() - height[i]; } } return water; } private int getHighestIdx(int[] height) { int high = 0; int idx = 0; for (int i = 0; i < height.length; i++) { if (height[i] > high) { high = height[i]; idx = i; } } return idx; } }