您的位置:首页 > 移动开发

Leetcode 42. Trapping Rain Water

2016-11-04 14:31 405 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 双指针