42. Trapping Rain Water

Problem:

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.

rainwatertrap

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

思路

设置左右2个指针,分别从左向右和从右向左遍历,保存2个变量max_left_height和max_right_height,当比他们小时说明可以存雨水,比他们大则更新max_left_height和max_right_height的值。

Solution (C++):

int trap(vector<int>& height) {
    if (height.empty())  return 0;
    int left = 0, right = height.size()-1, res = 0;
    int max_left_height = 0, max_right_height = 0;
    
    while (left <= right) {
        if (height[left] <= height[right]) {
            if (height[left] >= max_left_height)  max_left_height = height[left];
            else res += max_left_height - height[left];
            left++;
        }
        else {
            if (height[right] >= max_right_height)  max_right_height = height[right];
            else res += max_right_height - height[right];
            right--;
        }
    }
    return res;
}

性能

Runtime: 8 ms  Memory Usage: 9.1 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12290908.html