当前位置:网站首页>Monotonic stack -42 Connect rainwater
Monotonic stack -42 Connect rainwater
2022-07-03 08:36:00 【later_ rql】
Monotonic stack -42. Rainwater collection
1. subject
Given n Nonnegative integers indicate that each width is 1 Height map of columns of , Calculate columns arranged in this way , How much rain can be received after rain .

Example 1:
Input :height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output :6
explain : Above is an array of [0,1,0,2,1,0,1,3,2,1,2,1] Height map of representation , under these circumstances , Can connect 6 Units of rain ( The blue part indicates rain ).
Example 2:
Input :height = [4,2,0,3,2,5]
Output :9
source : Power button (LeetCode)
link :https://leetcode.cn/problems/trapping-rain-water
2. Their thinking
There are three ways to solve it :
Method 1 : Double finger needling

then , The height of rainwater in the current column is equal to ,min(LH,RH)- Current column height .
A special case : The first and last columns do not operate .
Method 2 : Dynamic programming
In fact, it is an optimization of the double pointer method , Because when using the double pointer method , Find out , When calculating the left and right maximum values of each column , There are repeated calculations , If dynamic programming method is used to record .
That is to traverse from left to right :maxLeft[i] = max(height[i], maxLeft[i - 1]);
Traverse from right to left :maxRight[i] = max(height[i], maxRight[i + 1]);
Method 3 : Monotonic stack

There are three situations :
(1) If the element currently traversed ( column ) The height is less than the height of the top element , Just add this element to the stack , Because the stack is supposed to keep the order from small to large ( From the top to the bottom of the stack ).
(2) If the element currently traversed ( column ) The height is equal to the height of the top element of the stack , To update the top of the stack elements , Because when you meet a column of the same height , You need to use the right most column to calculate the width .
(3) If the element currently traversed ( column ) The height is greater than the height of the top element , And then there's the groove ( In this case, there will be rain )
Its essence is : The top of the stack and the next element at the top of the stack, as well as the three elements to be put into the stack, will receive water !

Height of groove :int h = min(height[st.top()], height[i]) - height[mid];
Width of groove :int w = i - st.top() - 1 ;
Volume of groove :h*w
3. Code
Method 1 : Double finger needling ( Non optimal )
public int trap(int[] height) {
int sum = 0;
for (int i = 0; i < height.length; i++) {
// The first pillar and the last pillar don't receive rain
if (i==0 || i== height.length - 1) continue;
int rHeight = height[i]; // Record the highest height of the column on the right
int lHeight = height[i]; // Record the maximum height of the left column
for (int r = i+1; r < height.length; r++) {
if (height[r] > rHeight) rHeight = height[r];
}
for (int l = i-1; l >= 0; l--) {
if(height[l] > lHeight) lHeight = height[l];
}
int h = Math.min(lHeight, rHeight) - height[i];
if (h > 0) sum += h;
}
return sum;
}
Method 2 : Dynamic programming
public int trap(int[] height) {
int length = height.length;
if (length <= 2) return 0;
int[] maxLeft = new int[length];
int[] maxRight = new int[length];
// Record the maximum height of the left column of each column
maxLeft[0] = height[0];
for (int i = 1; i< length; i++) maxLeft[i] = Math.max(height[i], maxLeft[i-1]);
// Record the maximum height of the right column of each column
maxRight[length - 1] = height[length - 1];
for(int i = length - 2; i >= 0; i--) maxRight[i] = Math.max(height[i], maxRight[i+1]);
// Sum up
int sum = 0;
for (int i = 0; i < length; i++) {
int count = Math.min(maxLeft[i], maxRight[i]) - height[i];
if (count > 0) sum += count;
}
return sum;
}
Method 3 : Monotonous stack method
public int trap(int[] height){
int size = height.length;
if (size <= 2) return 0;
// in the stack, we push the index of array
// using height[] to access the real height
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
int sum = 0;
for (int index = 1; index < size; index++){
int stackTop = stack.peek();
if (height[index] < height[stackTop]){
stack.push(index);
}else if (height[index] == height[stackTop]){
// Because equal adjacent walls , The one on the left is impossible to store rainwater , therefore pop Sinister index, push Current index
stack.pop();
stack.push(index);
}else{
//pop up all lower value
int heightAtIdx = height[index];
while (!stack.isEmpty() && (heightAtIdx > height[stackTop])){
int mid = stack.pop();
if (!stack.isEmpty()){
int left = stack.peek();
int h = Math.min(height[left], height[index]) - height[mid];
int w = index - left - 1;
int hold = h * w;
if (hold > 0) sum += hold;
stackTop = stack.peek();
}
}
stack.push(index);
}
}
return sum;
}
4. performance
Method 1 : Double pointer ( Non optimal )
- Time complexity :O(n^2)
- Spatial complexity :O(l)
Method 2 : Dynamic programming
- Time complexity :O(n)
- Spatial complexity :O(n)
Method 3 : Monotonic stack
- Time complexity :O(n)
- Spatial complexity :O(n)
边栏推荐
- UE4 source code reading_ Bone model and animation system_ Animation compression
- Eating fruit
- Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données
- Mysql容器化(1)Docker安装MySQL
- 详解sizeof、strlen、指针和数组等组合题
- Golang string segmentation, substitution and interception
- 【K&R】中文第二版 个人题解 Chapter1
- Unity editor expansion - window, sub window, menu, right-click menu (context menu)
- Mall management system of database application technology course design
- Image processing 8-cnn image classification
猜你喜欢

Unity4.3.1 engine source code compilation process

Base64 and base64url

图像处理8-CNN图像分类

单调栈-84. 柱状图中最大的矩形

Base64和Base64URL

二进制转十进制,十进制转二进制

Unity interactive water ripple post-treatment
![[concurrent programming] working mechanism and type of thread pool](/img/51/d21428a7c95c0a5177e8198742e78c.jpg)
[concurrent programming] working mechanism and type of thread pool

简易入手《SOM神经网络》的本质与原理

Monotonic stack -503 Next bigger Element II
随机推荐
Mysql容器化(1)Docker安装MySQL
VIM learning notes from introduction to silk skating
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
Map的实现类的顺序性
Unity Editor Extension - Outline
[rust notes] 02 ownership
Vscode, idea, VIM development tool shortcut keys
[rust notes] 09- special types and generics
【Rust 笔记】07-结构体
Golang's range
Unity editor expansion - draw lines
Base64 and base64url
简易入手《SOM神经网络》的本质与原理
Notes on understanding applets 2022/7/3
Unity multi open script
[audio and video] ijkplayer error code
redis集群系列四
Delete the last character of the string in golang
Clion toolchains are not configured configure disable profile problem solving
Servlet的生命周期