LeetCode42 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.
这里写图片描述
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

题源:here;完整实现:here
思路:
4中方案:1 暴力搜索;2 动态规划;3 使用堆栈;4 使用两个指针。详细请参考:here
方案1

    int trap_1(vector<int>& height) {
        int result = 0;
        for (int i = 0; i < height.size(); i++){
            int leftMax = *max_element(height.begin(), height.begin()+i+1);
            int rightMax = *max_element(height.begin() + i, height.end());
            result += min(leftMax, rightMax) - height[i];
        }

        return result;
    }

方案2

    int trap_2(vector<int>& height){
        if (height.size() < 3) return 0;
        int hLen = height.size(), result = 0;
        vector<int> leftMax(hLen), rightMax(hLen);
        leftMax[0] = height[0]; rightMax[hLen - 1] = height[hLen - 1];
        for (int i = 1; i < hLen; i++) leftMax[i] = max(height[i], leftMax[i - 1]);
        for (int i = hLen - 2; i >= 0; i--) rightMax[i] = max(height[i], rightMax[i + 1]);

        for (int i = 0; i < hLen; i++) result += min(leftMax[i], rightMax[i]) - height[i];

        return result;
    }

方案3

int trap_3(vector<int>& height){
        if (height.size() < 3) return 0;
        stack<int> locs; locs.push(0);
        int result = 0, curr = 1;
        while (curr < height.size()){
            while (!locs.empty() && height[curr] > height[locs.top()]){
                int top = locs.top();
                locs.pop();
                if (locs.empty()) break;
                int distance = curr - locs.top() - 1;
                int boundH = min(height[locs.top()], height[curr]) - height[top];
                result += distance*boundH;
            }
            locs.push(curr++);
        }       

        return result;
    }

方案4

    int trap_4(vector<int>& height){
        if (height.size() < 3) return 0;
        int leftMax = 0, rightMax = 0, left = 0, right = height.size() - 1;
        int result = 0;
        while (left <= right){
            if (leftMax <= rightMax){
                if (height[left] < leftMax) result += leftMax - height[left++];
                else leftMax = height[left++];
            }
            else{
                if (height[right] < rightMax) result += rightMax - height[right--];
                else rightMax = height[right--];
            }
        }

        return result;
    }

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80813283