【LeetCode】Trapping Rain Water 2013年美团网校园招聘研发工程师笔试题
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!
Discuss
java code : lhs 对应能装水的台阶的左边界,rhs对应右边界,在这个边界确定的范围内,对每一个A[i] ,其能装到的水的大小为 min{左边最高值 ,右边界最高值} - A[i] if ( 该值 > A[i]) .我们预处理出这样一个左边界的最高值数组lheight[] ,然后从右边扫过来即可。算法的复杂度是O(n)。