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

posted @ 2020-02-10 14:41  littledy  阅读(92)  评论(0编辑  收藏  举报