【LeetCode】Trapping Rain Water 2013年美团网校园招聘研发工程师笔试题
2013-10-29 22:07
387 查看
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
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)。
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; } }
相关文章推荐
- 阿里巴巴2014秋季校园招聘-软件研发工程师笔试题详解
- 阿里巴巴2014秋季校园招聘-软件研发工程师笔试题详解
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 阿里巴巴2014秋季校园招聘-软件研发工程师笔试题 续
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 腾讯2015校园招聘研发工程师笔试题(西安站)
- 百度2014秋季校园招聘-软件研发工程师笔试题(2013年10月13日北京清华站)
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 百度2014校园招聘笔试题 ——深度学习算法研发工程师.
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 百度2015校园招聘笔试题——研发工程师(西安站)
- 整数无序数组求第K大数(暴力|快排) - 滴滴出行2018校园招聘内推笔试-研发工程师
- 2014阿里巴巴校园招聘研发工程师笔试题(北邮站)
- 百度2014校园招聘-研发工程师笔试题(济南站)
- 百度2014校园招聘研发工程师笔试题+答案
- 百度2014秋季校园招聘-软件研发工程师笔试题(2013年9月20日山东济南站)
- 阿里巴巴集团2014校园招聘笔试题------9-22北京 研发工程师
- 给定整数序列求连续子串最大和 - 滴滴出行2018校园招聘内推笔试-研发工程师
- 百度2014校园招聘-研发工程师笔试题(济南站)