---
title: "Trapping Rain Water"
author: "KickCode"
date: "2016-03-04T02:54:10Z"
tags: []
categories: ["编程语言"]
slug: "trapping-rain-water"
draft: false
lastmod: "2016-03-04T02:54:10Z"
id: 2280419
url: "https://kickcode.iteye.com/blog/2280419"
---

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 , return 6.
![](http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png)
The above elevation map is represented by array . In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

让我们计算出存水的总量，如果从左边依次计算，计算当前最高点和最低点之间的存水量，这样计算的结果小于实际的存水量，因为当前的最底点可能会被淹没(如果它两边有比它高的，它就会被淹没)。我们可以采用两个指针，从两边开始，找到一个最高点，然后再找到一个次高点，保持最高点不动，只移动次高点，次高点减去移动经过的柱子就是总的存水量。代码如下：

```java

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;
    }
}

```