上图索引位置值对应 数组 [0,1,0,2,1,0,1,3,2,1,2,1] 求上图蓝色方格(水滴)数量
public class Solution { public int trap(int[] height) { if (height == null || height.length<3){ return 0; } int max = 0; int maxIndex = 0; for(int i=0;imax){ max = height[i]; maxIndex = i; } } int leftMax = 0; int result = 0; for (int i=0;i =leftMax){ leftMax = height[i]; }else{ result += (leftMax-height[i]); //index索引上的存水量等于 左侧最大值-当前索引位置的值 } } int rightMax = 0; for (int i=height.length-1;i>maxIndex;i--){ if (height[i]>=rightMax){ rightMax = height[i]; }else{ result += (rightMax-height[i]); //index索引上的存水量等于 右侧最大值-当前索引位置的值 } } return result; }}