LintCode:接雨水

来源:互联网 发布:冒泡排序javascript 编辑:程序博客网 时间:2024/04/28 18:48

给出 n 个非负整数,代表一张X轴上每个区域宽度为 1 的海拔图, 计算这个海拔图最多能接住多少(面积)雨水。

接雨水

您在真实的面试中是否遇到过这个题?

Yes





样例

如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.

挑战

O(n) 时间, O(1) 空间

O(n) 时间, O(n) 空间也可以接受
标签 Expand   



相关题目 Expand   

解题思路:
方法1:O(n)时间,O(n)空间
该点雨水的存储,实际就是该点就是取左边最大值和右边最大值得更小的,减去改点的高度。
从左像右扫描,记录左边最大值,从右向左扫描记录右边最大值。

方法2:左右指针夹逼
该点雨水的存储,实际就是该点就是取左边最大值和右边最大值得更小的,减去改点的高度。
2个指针,一个在头,一个在尾。由于他们2者之间肯定有个最高点,相当于左指针的右最大值,相当于右指针的左最大值。

扫描一遍即可。

public class Solution {    /**     * @param heights: an array of integers     * @return: a integer     */    public int trapRainWater(int[] heights) {        // write your code here        int res = 0;         if(heights==null||0==heights.length) return res;         int len = heights.length;         int l = 0 ; int r = len-1;         int lmax = 0; int rmax = 0;         while(l<r){              lmax = Math.max(lmax, heights[l]);              rmax = Math.max(rmax, heights[r]);              if(lmax>rmax){                   res += rmax-heights[r];                   r--;              }else{                   res += lmax-heights[l];                   l++;              }         }         return res;    }}


0 0
原创粉丝点击