12、Trapping Rain Water

Problem Description

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.

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!

Analyze

1、找出最高的柱子,以此柱为中线将数组分为两半
2、处理左边一半:从左往右计算柱子高度极大值与当前柱子高度差
3、处理右边一半:从右往左同2

Code

class Solution {
    func trap(heights: [Int]) -> Int {
        let n = heights.count
        var water = 0
        var max: Int = 0
       
        for (i, value) in heights.enumerate() {
            if value > heights[max] {
                max = i //找出最高的柱子 将数组分为两半
            }
        }
        
        var peak = 0 // 谨记数据越界问题, 不能取heights[0]
         for value in heights[0..<max] {
            if value < peak {
                water += peak - value
            }
            else if value > peak {
                peak = value
            }
        }
        
        var top = 0
        for value in heights[max..<n].reverse() {
            if value < top {
                water += top - value
            }
            else if value > top {
                top = value
            }
        }
        
        return water
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 雨整夜,梦难寻, 辗转反侧照无眠,不闻窗外虫鸣声,唯闻檐下雨落声, 天晓欲曙时,却还昏暗,恍如入夜, 卧看斜雨纷纷...
    35f8a119f405阅读 94评论 0 2
  • 母亲已有六十九个日夜不曾跟我讲一句话。——开篇第一句话,就是有文字素描特色的文字,六十九个,这个明确的数字。 能在...
    April2005阅读 1,263评论 0 0
  • 没有结局博物馆之前是一座小镇。 小镇的人们把没有结局的故事留在房子里,然后带走了自己。 再后来,路过的旅客也常常在...
    喵喵僧阅读 480评论 5 6