雨水,lintcode

来源:互联网 发布:linux 退出vi 编辑:程序博客网 时间:2024/04/28 19:03

给出 n 个非负整数,代表一张X轴上每个区域宽度为 1 的海拔图, 计算这个海拔图最多能接住多少(面积)雨水。
样例
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.

一刷没有ac
解题思路:用两个指针像中间夹,记录左右保持的左最大和右最大,每次判断两者大小向中间移动,移动的时候计算res。时间O(n),空间O(1)。

public class Solution {    /**     * @param heights: an array of integers     * @return: a integer     */    public int trapRainWater(int[] heights) {        int res = 0;        if(heights == null || heights.length == 0) return res;        int lmax = 0, rmax = 0;        int l = 0;        int r = heights.length-1;        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;    }}

如果考虑时间O(n),空间O(n)的话,可以从左遍历纪录最大,然后从右遍历,开始计算右最大,在两者中取最小,在某点的水量应该是两者最小和此处高度的差

public class Solution {    /**     * @param heights: an array of integers     * @return: a integer     */    public int trapRainWater(int[] heights) {        if(heights == null || heights.length == 0) return 0;        int[] res = new int[heights.length];        int max = 0;        for(int i = 0; i < heights.length; i++){            max = Math.max(max, heights[i]);            res[i] = max;        }        max = 0;        int result = 0;        for(int i = heights.length - 1; i >= 0; i--){            max = Math.max(max,heights[i]);            result += Math.min(max, res[i]) - heights[i];        }        return result;    }}
0 0
原创粉丝点击