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

Trapping Rain Water

2016-07-14 09:02 323 查看
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.



Example

Given
[0,1,0,2,1,0,1,3,2,1,2,1]
, return
6
.

Analysis:

We first find out the max height in the array, then we start from the leftmost bar which is considered as the wall of the container. If there is a bar whose height is less than the wall, water will be saved above that bar. We do the same operation from rightmost to the highest bar position.

public class Solution {
/**
* @param heights: an array of integers
* @return: a integer
*/
public int trapRainWater(int[] A) {
if (A == null || A.length <= 2) return 0;
int maxIndex = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] > A[maxIndex]) {
maxIndex = i;
}
}
int leftMax = A[0];
int total = 0;
for (int i = 1; i < maxIndex; i++) {
if (A[i] < leftMax) {
total += (leftMax - A[i]);
} else {
leftMax = A[i];
}
}
int rightMax = A[A.length - 1];
for (int i = A.length - 2; i > maxIndex; i--) {
if (A[i] < rightMax) {
total += (rightMax - A[i]);
} else {
rightMax = A[i];
}
}
return total;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: