2022-5-5 预处理
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
1 class Solution { 2 public int trap(int[] height) { 3 int res=0,n=height.length; 4 5 int[] lmax=new int[n]; 6 int[] rmax=new int[n]; 7 lmax[0]=height[0]; 8 rmax[n-1]=height[n-1]; 9 for (int i=1;i<n;i++){ 10 lmax[i]=Math.max(height[i],lmax[i-1]); 11 } 12 for (int i=n-2;i>=0;i--){ 13 rmax[i]=Math.max(height[i],rmax[i+1]); 14 } 15 16 for (int i=0;i<n;i++){ 17 res+=Math.min(lmax[i],rmax[i])-height[i]; 18 } 19 return res; 20 } 21 }
思路:对于每个位置,接到的雨水为min(左边最大,右边最大)-当前值。直接处理两个最大值数组。