[LeetCode]42. Trapping Rain Water

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.

image

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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

我的解法

一开始我有一个错误的解法,这个解法是通过有穷自动机分析出来的;虽然这这种解法最终无法实现,但我发现有穷自动机真的是个逻辑分析的好工具,也算增长了经验

  • 先遍历一遍找出最大值,并假设一开始每一列都有着max高度的水;这个是个 O(N)的操作;
  • 而后从上至下,逐行地减去头和尾溢出的部分,这是个kO(N)的操作,k取决于最大的高度能有多大
  • 总结来说这是一个O(kN)的操作
func trap(height []int) int {
    
    if len(height) == 0{
        return 0;
    }
    
    // fill with the max;
    max := height[0]
    for _, val := range height {
        if max < val {
            max = val
        }
    }
    result := max * len(height)
    
    // delete the first 0 cols
    sp := 0
    for ; sp < len(height) && height[sp] == 0; sp++ {
        result -= max;
    }
    
    // delete the existing places
    for e:=sp; e<len(height); e++{
        result -= height[e];
    }
    
    // delete row by row
    for curH := max; curH >= 1; curH-- {
        
        // delete the head
        for e := sp;; e++ {
            if height[e] < curH {
                result--;
            } else{
                break;
            }
        }
        // delete the tail
        for e := len(height)-1;;e--{
            if height[e] < curH{
                result--;
            } else{
                break;
            }
        }
    }
    return result;
}

更巧妙的

讨论区里利用双指针,可以有 O(N)(只遍历一遍)的算法。具体看这里,这里不说详细的解析,简单来说就是左右同步扫描,并将水从低处往高处逐列填。这里只贴一下代码

class Solution {
public:
    int trap(int A[], int n) {
        int left=0; int right=n-1;
        int res=0;
        int maxleft=0, maxright=0;
        while(left<=right){
            if(A[left]<=A[right]){
                if(A[left]>=maxleft) maxleft=A[left];
                else res+=maxleft-A[left];
                left++;
            }
            else{
                if(A[right]>=maxright) maxright= A[right];
                else res+=maxright-A[right];
                right--;
            }
        }
        return res;
    }
};

更多的解法

Solution有更多的解法,还有一种动态规划的解法很有意思,将左边加起来,右边加起来,重叠部分就是所求。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 小女子不才, 没能与先生西楼掌灯, 所有豆蔻心思, 尽在一空残月之中。 小女子不才, 没能与先生煮豆调羹, 所有...
    巨蟹座的悲伤阅读 461评论 0 1
  • 生活是一望无际的荒漠,沙粒伴着一掊黄土,卷着一阵迷风,将水源藏在无处可无寻的岭头。 每当我提笔书写的时候总有点...
    有点幻想的花雯猫阅读 642评论 1 0
  • 先讲一个关于经学宗师爱新觉罗•毓鋆讲学的一个故事。他曾被尊为台湾绝无仅有的中国文化传人,据他的学生芝加哥大学教...
    修行中的gao阅读 583评论 0 3
  • 一个人的生命比一条鱼的生命更宝贵吗? 所有的人都活在其他的生命之上。我们得要一边活着,一边背负起对生命的业障以及责任。
    左边是我阅读 249评论 0 0
  • 文/玛雅天赋能量解读师 敏小姐 Hello,艺术家,你好。 打开你的玛雅盘,我试图进入你的宇宙,好喜悦的是我见到的...
    巫小敏阅读 3,706评论 0 5