【LeetCode】Trapping Rain Water 2013年美团网校园招聘研制工程师笔试题
【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)。
public class Solution { public int trap(int[] A) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int length = A.length; if(length <= 2) return 0; int lhs = 0, rhs = length - 1; while((lhs + 1) < length) { if(A[lhs + 1] >= A[lhs]) lhs++; else break; } while(rhs > 0) { if(A[rhs - 1] >= A[rhs]) rhs--; else break; } int[] lheight = new int[length]; int maxheight = A[lhs]; for(int i = lhs + 1; i < rhs; i++) { lheight[i] = maxheight; if(A[i] > maxheight) maxheight = A[i]; } maxheight = A[rhs]; int res = 0; for(int i = rhs - 1; i > lhs; i--) { int minheight = Math.min(maxheight, lheight[i]); if(minheight > A[i]) res += minheight - A[i]; if(A[i] > maxheight) maxheight = A[i]; } lheight = null; return res; } }