LeetCode's T42 catching rainwater (difficulty)

The topic of this explanation is a very interesting topic on LeetCode, and then put the topic:

T42. Rainwater (difficulty)

Insert picture description here
First of all, we have to know that the leftmost and rightmost pillars cannot receive water.
Secondly, if the index position can receive water, it means that there must be wood blocks larger than him on both sides of this position!
Problem-solving idea:
Assuming that the water does not depend on whether there is a column on the left, it only cares whether the column on the right is higher than the current index position, if it is higher, then it is assumed that the water level at the current position can reach the same height as the edged column, which can be obtained Bottom: In the
Insert picture description here
same way, looking from left to right, you can get the following:
Insert picture description here
Combining these two situations, and then placing the results for comparison, we can get: It
Insert picture description herecan be seen how to figure out how many water blocks can be placed in this position? Obviously, when the water depth at the same position of the current two pictures takes the smallest height, then the height at that position (the height of the original column plus the height of the water block) is the height of the current position, so we finally traverse from the beginning to the end, taking The minimum height of the two images minus the height of the black square is the number of water blocks at the current index position.
Next we upload the code:

class Solution {
    public int trap(int[] height) {
        if (height.length==0) //判断长度为0的情况
        return 0;
        int sum=0;
        int[] except_left=new int[height.length];  // 忽略因为左边的墙而不能装水的情况
        int[] except_right=new int[height.length];  // 忽略因为右边边的墙而不能装水的情况
        except_right[0]=height[0];
        for(int i=1;i<height.length;i++){
            except_right[i]=height[i]<except_right[i-1]? except_right[i-1]:height[i];
        }
        except_left[height.length-1]=height[height.length-1];
        for(int i=height.length-2;i>=0;i--){
            except_left[i]=height[i]<except_left[i+1]? except_left[i+1]:height[i];
        }
        //由头到尾进行计算当前索引位置上的水块
        for(int i=0;i<height.length;i++){
            sum+=Math.min(except_left[i],except_right[i])-height[i];
        }
        return sum;
    }
}

Insert picture description here
This time the topic is explained, if there is something wrong, you are welcome to give pointers, thank you!

Guess you like

Origin blog.csdn.net/Pzzzz_wwy/article/details/105500767