题目
描述
给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个柱子高度图,计算按此排列的柱子,下雨之后能接多少雨水。(数组以外的区域高度视为0)
要求:时间复杂度 O(n)
示例1
输入:[3,1,2,5,2,4]
返回值:5
说明:
数组 [3,1,2,5,2,4] 表示柱子高度图,在这种情况下,可以接 5个单位的雨水,蓝色的为雨水 ,如题中的图。
示例2
输入:[4,5,1,3,2]
返回值:2
核心代码块
import java.util.*;
public class Solution {
/**
* max water
* @param arr int整型一维数组 the array
* @return long长整型
*/
public long maxWater (int[] arr) {
// write code here
int res = 0;
//确定双指针的起始位置
int left = 0;
int right = arr.length-1;
int maxL = 0;
int maxR = 0;
while(left<right){
//每次维护往中间的最大边界
maxL = Math.max(maxL,arr[left]);
maxR = Math.max(maxR,arr[right]);
//较短的边界确定该格子的水量
if(maxR>maxL)
res +=maxL-arr[left++];
else
res +=maxR-arr[right--];
}
return res;
}
}