LeetCode Brushing Notes_42. Receiving Rain

The topic is from LeetCode

Other solutions or source code can be accessed: tongji4m3

description

Given n non-negative integers representing the height map of each column with a width of 1, calculate how much rain water can be received by the columns arranged in this way.

The above is the height map represented by the array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain (blue Part means rain).

Example:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

Ideas

Find the highest position on the left: traverse from left to right

Find the highest position on the right: traverse from right to left

Find the highest height on the left and the highest height on the right of each location, and take the smaller one-the height of that location. That is the rainwater at that location

Accumulate the rainwater collected at each location

Code

public int trap(int[] height)
{
    
    
    int n = height.length;
    if (n <= 2) return 0;//接不了雨水
    int[] left = new int[n];
    int[] right = new int[n];

    left[0] = height[0];
    for (int i = 1; i < n; i++) left[i] = Math.max(left[i - 1], height[i]);

    right[n - 1] = height[n - 1];
    for (int i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], height[i]);

    int result = 0;

    for (int i = 0; i < n; i++) result += (Math.min(left[i], right[i]) - height[i]);
    return result;
}

Complexity analysis

time complexity

O (N) O (N) O ( N ) , three cycles, each time requires N, a total of 3N

Space complexity

O (N) O (N) O ( N ) , define two arrays of size N, the total space required is 2N

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108163112