42.接雨水
42.接雨水
题目
给定 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
找到第一个大得元素就可以开始接雨水了。
这里需要在一维数组中找到右边第一个大于的元素,符合单调栈的使用场景,这里可以使用单调栈。
这里我们需要解决两个问题
- 找到右边第一个大于的元素
- 如何计算每一轮能接的雨水
右边第一个大于的元素
 for (int i = 0; i < height.length; i++) {
      while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
		  //找到右边第一个比它大的元素
	  }
	  stack.push(i);
}
如何计算能接的雨水

凹槽左右两边小的那个高度-凹槽的高度 = 高
比它大的第一个元素的下标 - 左边的下标 - 1= 长
能接的雨水=长*高
for (int i = 0; i < height.length; i++) {
      while (!st.empty() && height[st.peek()] < height[i]) {
		 right=i; //右边第一个大得元素下标作为右边界
		 cur =  st.pop();; //做凹槽得部分,可以接雨水得部分,凹槽部分出栈可以想象为对下一轮该凹槽被填满了
		 if(st.empty())break; //凹槽部分是第一个元素不接水
		 left = st.peek(); //左边界的下标
		 h = Math.min(height[left],height[right])-height[cur];
		 result +=(right-left-1) *h;
	  }
	  st.push(i);
}
代码
class Solution {
    public int trap(int[] height) {
        int len = height.length;
        if(len==1)return 0;
        int h;
        int left = 0;
        int right = 0;
        int result = 0;
        int cur;                 
        Stack <Integer> st = new Stack<>(); 
     for (int i = 0; i < height.length; i++) {
      while (!st.empty() && height[st.peek()] < height[i]) {
		 right=i; //右边第一个大得元素下标作为右边界
		 cur =  st.pop();; //做凹槽得部分,可以接雨水得部分
         if(st.empty())break; //凹槽部分是第一个元素不接水
		 left = st.peek(); //左边界的下标
		 h = Math.min(height[left],height[right])-height[cur];
		 result +=(right-left-1) *h;
	  }
	  st.push(i);
}
    return result;
}
}
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号