Leetcode 42. Trapping Rain Water

来源:互联网 发布:手机拍照后期制作软件 编辑:程序博客网 时间:2024/03/29 05:13

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.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
这里写图片描述

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!

大致意思是求条形图形的蓄水能力。也即图中的蓝色阴影面积。

这里说下思路以备用:
首先看到这题的时候并没有什么思路来做,后来看了下标签,提示是双指针。然后思考:什么样的情况下可以蓄水?蓄水面积要如何计算?不妨考虑某个时刻两端的高度为left和right。此时,则应该从低向高位扩展,并且有扩展过程可以计算经过路径的蓄水面积。

public int trap(int[] height) {        if (height == null || height.length < 3) {            return 0;        }        int res = 0;        int left = 0, right = height.length - 1;        while (left < right) {            int min = height[left] > height[right] ? height[right] : height[left];            if (min == height[left]) {                while (++left < right && height[left] <= min) {                    res += min - height[left];                }            } else {                while (left < --right && height[right] <= min) {                    res += min - height[right];                }            }        }        return res;    }
0 0
原创粉丝点击