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.

42. Trapping Rain Water_第1张图片

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& 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

你可能感兴趣的:(42. Trapping Rain Water)