leetcode-42. Trapping Rain Water

来源:互联网 发布:cctv视频下载软件 编辑:程序博客网 时间:2024/04/30 08:08

leetcode-42. Trapping Rain Water

题目:

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.

基本上就是两点法,i和j分别从两端开始向中心移动。同事维护一个i和j之外最高的容器高度h就行,凡是低于h的i和j的值说明都有水。

public class Solution {    public int trap(int[] height) {        if(height==null || height.length <1) return 0;        int i = 0, j = height.length-1,ret = 0,h=Math.min(height[i],height[j]);        while(i<j){            ret += h>height[i]? h-height[i] : 0;            ret += h>height[j]? h-height[j] : 0;            h = Math.max(h,Math.min(height[i],height[j]));            if(height[i]<height[j])                i++;            else                j--;        }        return ret;    }}
0 0
原创粉丝点击