算法题:接雨水

一、题目

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

二、思路

从左往右看,只要left指针所指的值比前面的值要小,此时就肯定能蓄水,其蓄水面积为left_max - height[left];
从右往左看,只要right指针所指的值小于后面的值,此时就肯定能蓄水,其蓄水面积为right_max - height[right]。

三、实现

public int trap(int[] height) {
        int left = 0;
        int right = height.length - 1;

        int left_max = 0;
        int right_max = 0;

        int result = 0;

        while (left < right) {
            if (height[left] <= height[right]) {
                left_max = Math.max(height[left], left_max);

                if(height[left] < left_max) {
                    result += left_max - height[left];
                }

                left ++;
            } else {
                right_max = Math.max(height[right], right_max);
                if(height[right] < right_max) {
                    result = result + right_max - height[right];
                }
                
                right --;
            }
        }

        return result;
    }

发布了83 篇原创文章 · 获赞 0 · 访问量 4524

猜你喜欢

转载自blog.csdn.net/zhangdx001/article/details/105455728