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!

让我们计算出存水的总量,如果从左边依次计算,计算当前最高点和最低点之间的存水量,这样计算的结果小于实际的存水量,因为当前的最底点可能会被淹没(如果它两边有比它高的,它就会被淹没)。我们可以采用两个指针,从两边开始,找到一个最高点,然后再找到一个次高点,保持最高点不动,只移动次高点,次高点减去移动经过的柱子就是总的存水量。代码如下:
public class Solution {
    public int trap(int[] height) {
        if(height == null || height.length < 3) return 0;
        int left = 0;
        int right = height.length - 1;
        int secondMaxHeight = Integer.MIN_VALUE;
        int area = 0;
        while(left < right) {
            if(height[left] < height[right]) {
                secondMaxHeight = Math.max(secondMaxHeight, height[left]);
                area += secondMaxHeight - height[left];
                left ++;
            } else {
                secondMaxHeight = Math.max(secondMaxHeight, height[right]);
                area += secondMaxHeight - height[right];
                right --;
            }
        }
        return area;
    }
}

你可能感兴趣的:(双指针)