当前位置:网站首页>Connected to rainwater series problems
Connected to rainwater series problems
2022-06-29 00:52:00 【GreyZeng】
Connected to rainwater series problems
author :Grey
Original address : Connected to rainwater series problems
LeetCode 42. Rainwater collection
Main idea : Consider each location , How much water can be left on the top , Add up , Is the total receiving water .
among , The rightmost and leftmost tops do not receive water , Because the water will flow away from both sides .

Based on the above logic , At least we can judge , If the length of the array is less than or equal to 2, Go straight back to 0 Share water .
When the length of the array is greater than 2, We need to consider , from 1 No. 1 to The length of the array -2, How much water can be connected to the top of each position .
Set four variables
int l = 1;
int r = arr.length - 2;
// What is the bottleneck of the current height on the left side
int lMax = arr[0];
// What is the bottleneck of the current height on the right
int rMax = arr[arr.length - 1];
lMax and rMax As the bottleneck of the left and right sides in the current state , Where we actually traverse from l To r, look down arr[l] and arr[r] The location is based on the amount of water that can be collected by the bottlenecks on the left and right sides .

First , Although there are two bottleneck values , however , When we settle accounts , It can only be settled with a small bottleneck value , Because if you settle with a large bottleneck value , A small bottleneck will lower the current settlement value ( Barrel effect ).
therefore , There are two situations :
Situation 1 :lMax > rMax
Situation two :lMax <= rMax
In this case , for example

under these circumstances , We can be sure arr[r] How much water can be connected to the position , because arr[r] And the bottleneck on the right is a definite relationship , Although the bottleneck on the left is smaller than arr[r] Big , It's the water that makes the right bottleneck arr[r] The collected water flows away , So at this time
arr[r] The amount of water that can be collected on the is arr[r] and rMax Difference between , If it's a negative number , Then for 0, Equivalent to not receiving water , here ,r Position traversal completed , The bottleneck on the right is updated to Math.max(arr[r],rMax), Follow the example above , Now the bottleneck on the right becomes arr[r] Value on . Here's the picture

In this state , The relatively small bottleneck is rMax, You can also settle the current arr[r] The amount of water at the location , still 0. Then continue to update the right bottleneck , Here's the picture

here , The bottleneck on the left is the smaller one , Update now arr[l] The amount of water overhead , namely :arr[l] and lMax The difference between and 0 The bigger one , And then move l The pointer , Update the bottleneck on the left ( because arr[l] No value lMax Big , So the bottleneck on the left side remains the same lMax Location ), Here's the picture .

Next lMax < rMax, Continue settlement arr[l], Move l And update lMax

The following process is the same , The schematic diagram is as follows

until l>r

All water is collected .
For the full code, see
public static int trap(int[] arr) {
if (arr == null || arr.length <= 2) {
return 0;
}
int result = 0;
int l = 1;
int r = arr.length - 2;
int lMax = arr[0];
int rMax = arr[arr.length - 1];
while (l <= r) {
if (lMax < rMax) {
// Settlement left
result += Math.max(0, lMax - arr[l]);
lMax = Math.max(lMax, arr[l++]);
} else {
// Settlement right side
result += Math.max(0, rMax - arr[r]);
rMax = Math.max(rMax, arr[r--]);
}
}
return result;
}
Time complexity O(N), Spatial complexity O(1).
LeetCode 407. Rainwater collection II
Main idea
It's the same as one-dimensional thinking , The problem of two-dimensional rainwater connection is also to locate the bottleneck first , The bottleneck of one-dimensional rainwater connection is located from the left and right ends , The two-dimensional bottleneck is to locate around the matrix . To find the smallest bottleneck around , We need to use one Heap ( Organize by value ), Add the values of four weeks to the small root heap , The pop-up value is the minimum bottleneck . First , We need to wrap the original matrix , To design a Node data structure , It is used to store a certain value and its position information in the original matrix .
public static class Node {
public int v; // value
public int i; // Row position
public int j; // Column position
public Node(int v, int i, int j) {
this.i = i;
this.j = j;
this.v = v;
}
}
What is stored in the small root pile is Node, according to Node Of v To organize ,
PriorityQueue<Node> heap = new PriorityQueue<>(Comparator.comparingInt(o -> o.v));
Every time a Node When , Move this position up, down, left and right ( Make sure you don't cross the line ) To settle , After settlement , Add the settled position to the small root heap ( There is no need to add the positions that have already been added ), Because you need to know which locations have been added to the small root heap , So set a two-dimensional boolean Array , Used to mark whether a certain position has been entered .
boolean[][] isEntered = new boolean[m][n];
if (isEntered[i][j]) {
// A certain location has entered the small root pile
} else {
// Otherwise, I have not entered
}
First , We add the points around the matrix to the small root pile , And the isEntered Set it up
// Here are two for loop , Is to put all around into a pile of small roots
for (int i = 0; i < m; i++) {
heap.offer(new Node(heightMap[i][0], i, 0));
heap.offer(new Node(heightMap[i][n - 1], i, n - 1));
isEntered[i][0] = true;
isEntered[i][n - 1] = true;
}
for (int i = 0; i < n; i++) {
heap.offer(new Node(heightMap[0][i], 0, i));
heap.offer(new Node(heightMap[m - 1][i], m - 1, i));
isEntered[0][i] = true;
isEntered[m - 1][i] = true;
}
Then we set up a max, It is used to identify which is the smallest bottleneck at this time . The next process is :
One element pops up from the small root heap at a time , See if you can update the bottleneck value , Let's see if its position in all directions crosses the boundary , If you don't cross the border , Direct settlement of values in all directions , Add up to water In this variable , At the same time, all directions Node Add the small root pile , cycle , Until the small root heap is empty .water The value of is the amount of water collected .
For the full code, see
public static int trapRainWater(int[][] heightMap) {
if (null == heightMap || heightMap.length <= 2 || heightMap[0].length <= 2) {
return 0;
}
int m = heightMap.length;
int n = heightMap[0].length;
int max = 0;
PriorityQueue<Node> heap = new PriorityQueue<>(Comparator.comparingInt(o -> o.v));
boolean[][] isEntered = new boolean[m][n];
// Here are two for loop , Is to put all around into a pile of small roots
for (int i = 0; i < m; i++) {
heap.offer(new Node(heightMap[i][0], i, 0));
heap.offer(new Node(heightMap[i][n - 1], i, n - 1));
isEntered[i][0] = true;
isEntered[i][n - 1] = true;
}
for (int i = 0; i < n; i++) {
heap.offer(new Node(heightMap[0][i], 0, i));
heap.offer(new Node(heightMap[m - 1][i], m - 1, i));
isEntered[0][i] = true;
isEntered[m - 1][i] = true;
}
int water = 0;
while (!heap.isEmpty()) {
// The weakest position
Node weakest = heap.poll();
max = Math.max(weakest.v, max);
int i = weakest.i;
int j = weakest.j;
if (i + 1 < m && !isEntered[i + 1][j]) {
water += Math.max(0, max - heightMap[i + 1][j]);
isEntered[i + 1][j] = true;
heap.offer(new Node(heightMap[i + 1][j], i + 1, j));
}
if (i - 1 >= 0 && !isEntered[i - 1][j]) {
water += Math.max(0, max - heightMap[i - 1][j]);
isEntered[i - 1][j] = true;
heap.offer(new Node(heightMap[i - 1][j], i - 1, j));
}
if (j + 1 < n && !isEntered[i][j + 1]) {
water += Math.max(0, max - heightMap[i][j + 1]);
isEntered[i][j + 1] = true;
heap.offer(new Node(heightMap[i][j + 1], i, j + 1));
}
if (j - 1 >= 0 && !isEntered[i][j - 1]) {
water += Math.max(0, max - heightMap[i][j - 1]);
isEntered[i][j - 1] = true;
heap.offer(new Node(heightMap[i][j - 1], i, j - 1));
}
}
return water;
}
public static class Node {
public int v;
public int i;
public int j;
public Node(int v, int i, int j) {
this.i = i;
this.j = j;
this.v = v;
}
}
Spatial complexity O(M*N), The time complexity is O(M*N*log(M+N)).
more
边栏推荐
- Structure of the actual combat battalion | module 5
- Install MySQL on Windows platform (with Navicat premium 12 "using" tutorial)
- Précautions d'installation et d'utilisation des joints rotatifs
- 请问同花顺上开户安全吗
- [image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code
- pinhole camera model
- Operation level smart campus system source code smart campus applet source code + electronic class card + face recognition system
- Is it safe to open an account on the flush
- Matrix compression
- Is it safe to open an account on great wisdom
猜你喜欢
![[leetcode] 522. 最长特殊序列 II 暴力 + 双指针](/img/88/3ddeefaab7e29b8eeb412bb5c3e9b8.png)
[leetcode] 522. 最长特殊序列 II 暴力 + 双指针

旋轉接頭安裝使用注意事項

最新Justnews主题源码6.0.1开心版+社交问答插件2.3.1+附教程
![[MCU club] design of classroom number detection based on MCU [simulation design]](/img/87/6dc27c90c9f9d26a6338b3618e974b.jpg)
[MCU club] design of classroom number detection based on MCU [simulation design]

流媒体集群应用与配置:如何在一台服务器部署多个EasyCVR?
![[MCU club] design of blind water cup based on MCU [physical design]](/img/06/93d7a8fd97cdccbc639d2a95b10826.jpg)
[MCU club] design of blind water cup based on MCU [physical design]

Baidu online disk login verification prompt: unable to access this page, or the QR code display fails, the pop-up window shows: unable to access this page, ensure the web address....
![[image registration] improved SAR image registration based on sar-sift with matlab code](/img/69/4e78c6cef45b2e4d133222a4372e43.jpg)
[image registration] improved SAR image registration based on sar-sift with matlab code

Successfully solved (machine learning data segmentation problem): modulenotfounderror: no module named 'sklearn cross_ validation‘

Haskell configuring vs code development environment (june2022)
随机推荐
[staff] accent mark, gradually stronger mark and gradually weaker mark
旋转接头安装使用注意事项
Comparison between winding process and lamination process
IT治理方面的七个错误,以及如何避免
[SV basics] some usage of queue
【架构师(第三十八篇)】 服务端开发之本地安装最新版 MySQL 数据库
[leetcode] 522. 最长特殊序列 II 暴力 + 双指针
请问同花顺上开户安全吗
FATAL ERROR: Could not find ./ bin/my_ print_ Solutions to defaults
大型网站架构基础之笔记
be based on. NETCORE development blog project starblog - (13) add friendship link function
同期群分析是什么?教你用 SQL 来搞定
Ensemble de données sur les visages masqués et méthode de génération des visages masqués
Bmfont make bitmap font and use it in cocoscreator
Two ways to set up a single Nacos load balancing ribbon polling policy weight
旋轉接頭安裝使用注意事項
[MCU club] design of classroom number detection based on MCU [physical design]
Analysis Framework -- establishment of user experience measurement data system
运营级智慧校园系统源码 智慧校园小程序源码+电子班牌+人脸识别系统
[Architect (Part 38)] locally install the latest version of MySQL database developed by the server