其他分享
首页 > 其他分享> > [leetcode] 42. Trapping Rain Water

[leetcode] 42. Trapping Rain Water

作者:互联网

Description

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.
trap rain water
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

分析

题目的意思是:给你一个柱形图,然后往里面注水,问柱形图能够装得下多大面积的水。

代码

class Solution {
public:
    int trap(vector<int>& height) {
        int i=0;
        int j=height.size()-1;
        int sum=0;
        int left_max=0;
        int right_max=0;
        while(i<j){
            left_max=max(left_max,height[i]);
            right_max=max(right_max,height[j]);
            if(left_max<right_max){
                sum+=(left_max-height[i]);
                i++;
            }else{
                sum+=(right_max-height[j]);
                j--;
            }
        }
        return sum;
    }
};

参考文献

42. Trapping Rain Water

标签:water,elevation,int,最大值,42,Water,trap,leetcode
来源: https://blog.csdn.net/w5688414/article/details/97616015