Leetcode 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.
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!
标签
类似的题目
思路:两头指针,一个柱体一个柱体遍历,有可以积水的直接加。对于[left,right],height[left]表示的是“碗”左边高度,height[right]表示的是“碗”右边高度,level表示的是当前“碗”的最高盛水高度,lower=min(height[left],height[right])。
代码:
1 public class Solution { 2 public int trap(int[] height) { 3 int water = 0, lower = 0, level = 0, left = 0, right = height.length - 1; 4 while(left < right) { 5 lower = height[height[left] <= height[right] ? left++ : right--]; 6 level = Math.max(level, lower); 7 water += level - lower; 8 } 9 return water; 10 } 11 }