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.

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!

思路分析:从左至右,针对当前的高度,往右寻找,如果有大于等于当前高度的元素,则说明水平线应该拉到这儿,否则,应该找到在后面元素中相对最大的元素(如果有很多,则应该返回第一个元素)。cur指向这个返回的元素。

class Solution {
public:
    int next(vector<int>& height, int pos){//若果pos位置后面有大于等于height[pos]直接返回第一个这样的值的位置,否则,返回后续中(最大的高度并且是第一次出现)的下标位置
        if (pos >= height.size() - 1)//遍历到最后一个元素时,就应该结束了,因为蓄不了水
            return -1;
        int val = height[pos];
        int start = height[pos + 1];
        int res = pos + 1;
        for (int i = pos + 1; i<height.size(); i++)
        {
            if (height[i] >= val){//情况之一,后面元素存在大于等于当前元素高度的值
                return i;
            }
            else if (height[i]>start){//情况之二,记录后面元素中相对最大的元素,并且是第一次出现的元素
                res = i;
                start = height[i];
            }
        }
        return res;
    }
    int trap(vector<int>& height) {
        if(height.size()==0)
            return 0;
        int result = 0;
        int start = 0;
        while (height[start] == 0){
            start++;
        }
        while (start<height.size()-1){
            int cur = next(height, start);
            int altitude = height[start]<height[cur] ? height[start] : height[cur];
            for (int i = start + 1; i<cur; i++){
                result += (altitude - height[i]);
            }
            start = cur;
        }
        return result;
    }
};
手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
原文地址:https://www.cnblogs.com/chess/p/5307157.html