42. 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.


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 Marcosfor contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6


 
  public int trap(int[] heights) {

        if (heights.length <= 2) {
            return 0;
        }

        int left = 0, right = heights.length - 1, totalArea = 0;
        int leftMaxHeight = heights[left], rightMaxHeight = heights[right];

        while (left < right) {
            if (heights[left] < heights[right]) {
                leftMaxHeight = Math.max(leftMaxHeight, heights[++left]);
                totalArea += leftMaxHeight - heights[left];
            } else {
                rightMaxHeight = Math.max(rightMaxHeight, heights[--right]);
                totalArea += rightMaxHeight - heights[right];
            }
        }

        return totalArea;
    }

 

Complexity analysis

  • Time complexity: O(n)O(n). Single iteration of O(n)O(n).
  • Space complexity: O(1)O(1) extra space. Only constant space required for leftright, left_max and right_max.

 

 

 

posted @ 2018-06-26 12:11  VickyFengYu  阅读(100)  评论(0编辑  收藏  举报