尚云网站建设,WordPress文章采集软件,网络传媒公司注册经营范围,青岛房产给定 n 个非负整数表示每个宽度为 1 的柱子的高度图#xff0c;计算按此排列的柱子#xff0c;下雨之后能接多少雨水。 示例 1#xff1a;输入#xff1a;height [0,1,0,2,1,0,1,3,2,1,2,1]
输出#xff1a;6
解释#xff1a;上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表…给定 n 个非负整数表示每个宽度为 1 的柱子的高度图计算按此排列的柱子下雨之后能接多少雨水。 示例 1输入height [0,1,0,2,1,0,1,3,2,1,2,1]
输出6
解释上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图在这种情况下可以接 6 个单位的雨水蓝色部分表示雨水。
示例 2输入height [4,2,0,3,2,5]
输出9有待学习
提示n height.length
1 n 2 * 10^4
0 height[i] 10^5class Solution {public int trap(int[] height) {int ans 0;DequeInteger stack new LinkedListInteger();int n height.length;for (int i 0; i n; i) {while (!stack.isEmpty() height[i] height[stack.peek()]) {int top stack.pop();if (stack.isEmpty()) {break;}int left stack.peek();int currWidth i - left - 1;int currHeight Math.min(height[left], height[i]) - height[top];ans currWidth * currHeight;}stack.push(i);}return ans;}
}