classSolution{publicinttrap(int[] height){if(height.length ==0){return0;}int sum =0;Stack<Integer> st =newStack<>();
st.push(0);for(int i =1; i < height.length;i++){if(height[i]<= height[st.peek()]){
st.push(i);}else{while(!st.isEmpty()&& height[i]> height[st.peek()]){int right = i;int mid = st.peek();
st.pop();if(!st.isEmpty()){int left = st.peek();int h =Math.min(height[left],height[right])-height[mid];int width = right-left-1;int nowArea = h*width;
sum+=nowArea;}}
st.push(i);}}return sum;}}
3- ACM 实现
publicclass trap {publicstaticinttrap(int[] nums){Stack<Integer> st =newStack<>();int res =0;// 遍历
st.push(0);for(int i =1; i <nums.length;i++){if(nums[i]<=nums[st.peek()]){
st.push(i);}else{while(!st.isEmpty()&& nums[i]> nums[st.peek()]){int right = i;int mid = st.peek();
st.pop();if(!st.isEmpty()){int left = st.peek();int h =Math.min(nums[left],nums[right])-nums[mid];int width = right-left-1;int nowArea = width*h;
res+=nowArea;}}
st.push(i);}}return res;}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);System.out.println("输入数组长度");int n = sc.nextInt();int[] nums =newint[n];for(int i =0; i < n ;i++){
nums[i]= sc.nextInt();}System.out.println("结果是"+trap(nums));}}