publicinttrap(int[] height){ if (height==null||height.length<3)return0; int ans=0,maxHeight=height[0]; for (int h : height)if (h>maxHeight)maxHeight=h; for (int row = 1; row <= maxHeight; row++) { int temp=0; //是否开始统计temp boolean isStart=false; for (int i = 0; i < height.length; i++) { if (isStart&&height[i]<row)temp++; if (height[i]>=row){ ans+=temp; temp=0; isStart=true; } } } return ans; }
publicinttrap(int[] height){ if (height==null||height.length<3)return0; int ans=0; for (int col = 0; col < height.length; col++) { //找到col左右最高的墙 int leftMax=0; for (int i = col-1; i >=0; i--) leftMax=Math.max(leftMax,height[i]); int rightMax=0; for (int i = col+1; i < height.length; i++) rightMax=Math.max(rightMax,height[i]); //如果最高的墙中最矮的一个大于col的高度,计算当前列上接的水并加入结果 if (Math.min(leftMax,rightMax)>height[col])ans+=Math.min(leftMax,rightMax)-height[col]; } return ans; }
publicinttrap(int[] height){ if (height==null||height.length<3)return0; //计算leftMax,rightMax int[] leftMax=newint[height.length],rightMax=newint[height.length]; for (int i = 1; i < height.length; i++) leftMax[i]=Math.max(leftMax[i-1],height[i-1]); for (int i=height.length-2;i>=0;i--) rightMax[i]=Math.max(rightMax[i+1],height[i+1]); //计算每一列上的水 int ans=0; for (int i = 1; i < height.length-1; i++) { int min=Math.min(leftMax[i],rightMax[i]); if (min>height[i]){ ans+=min-height[i]; } } return ans; }
publicinttrap(int[] height){ if (height==null||height.length<3)return0; int leftMax=0,rightMax=0,ans=0,left=1,right=height.length-2; while (left<=right){ //计算更新leftMax rightMax leftMax=Math.max(leftMax,height[left-1]); rightMax=Math.max(rightMax,height[right+1]); //比较leftMax和rightMax,找到较低的那一侧 if (leftMax<rightMax){ if (leftMax>height[left])ans+=leftMax-height[left]; left++; }else { if (rightMax>height[right])ans+=rightMax-height[right]; right--; } } return ans; }