Trapping Rain Water I && II
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Analysis:
We first find out the max height in the array, then we start from the leftmost bar which is considered as the wall of the container. If there is a bar whose height is less than the wall, water will be saved above that bar. We do the same operation from rightmost to the highest bar position.
public class Solution {
public int trap(int[] height) {
if (height == null || height.length <= ) return ;
int maxIndex = ;
for (int i = ; i < height.length; i++) {
if (height[i] > height[maxIndex]) {
maxIndex = i;
}
}
int leftMax = height[];
int total = ;
for (int i = ; i < maxIndex; i++) {
if (height[i] < leftMax) {
total += (leftMax - height[i]);
} else {
leftMax = height[i];
}
}
int rightMax = height[height.length - ];
for (int i = height.length - ; i > maxIndex; i--) {
if (height[i] < rightMax) {
total += (rightMax - height[i]);
} else {
rightMax = height[i];
}
}
return total;
}
}
Trapping Rain Water II
Given an m x n
matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
] Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
before the rain.
After the rain, water is trapped between the blocks. The total volume of water trapped is 4.
分析:
从四周出发,选取最低点(木桶原理),然后选取周围没有被visited的点。找到更低的点,则把当前点和低点的差值作为可以装水的量,注意,在加入新的点的时候,那个点的高度应该使用当前点的高度,这样我们就不用倒着回去找最高点了。
class Solution {
public int trapRainWater(int[][] heights) {
if (heights == null || heights.length == || heights[].length == ) return ; PriorityQueue<Cell> queue = new PriorityQueue<>(, (cell1, cell2) -> cell1.height - cell2.height);
int row = heights.length, col = heights[].length;
boolean[][] visited = new boolean[row][col]; // add border cells to the queue.
for (int i = ; i < row; i++) {
visited[i][] = true;
visited[i][col - ] = true;
queue.offer(new Cell(i, , heights[i][]));
queue.offer(new Cell(i, col - , heights[i][col - ]));
} for (int i = ; i < col; i++) {
visited[][i] = true;
visited[row - ][i] = true;
queue.offer(new Cell(, i, heights[][i]));
queue.offer(new Cell(row - , i, heights[row - ][i]));
} // from the borders, pick the shortest cell visited and check its neighbors:
// if the neighbor is shorter, collect the water it can trap and update its height as its height plus the water trapped
// add all its neighbors to the queue.
int[][] dirs = new int[][]{{-, }, {, }, {, -}, {, }};
int res = ;
while (!queue.isEmpty()) {
Cell cell = queue.poll();
for (int[] dir : dirs) {
int neighbor_row = cell.row + dir[];
int neighbor_col = cell.col + dir[];
if (neighbor_row >= && neighbor_row < row && neighbor_col >= && neighbor_col < col && !visited[neighbor_row][neighbor_col]) {
visited[neighbor_row][neighbor_col] = true;
res += Math.max(, cell.height - heights[neighbor_row][neighbor_col]);
queue.offer(new Cell(neighbor_row, neighbor_col, Math.max(heights[neighbor_row][neighbor_col], cell.height)));
}
}
}
return res;
}
} class Cell {
int row;
int col;
int height;
public Cell(int row, int col, int height) {
this.row = row;
this.col = col;
this.height = height;
}
}
Trapping Rain Water I && II的更多相关文章
- leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II
11. Container With Most Water https://www.cnblogs.com/grandyang/p/4455109.html 用双指针向中间滑动,较小的高度就作为当前情 ...
- [LeetCode] Trapping Rain Water II 收集雨水之二
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] 407. Trapping Rain Water II 收集雨水之二
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] 407. Trapping Rain Water II 收集雨水 II
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- [LeetCode] Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- [LeetCode] 42. Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- [LintCode] Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- LeetCode:Container With Most Water,Trapping Rain Water
Container With Most Water 题目链接 Given n non-negative integers a1, a2, ..., an, where each represents ...
- LeetCode - 42. Trapping Rain Water
42. Trapping Rain Water Problem's Link ------------------------------------------------------------- ...
随机推荐
- fs.mkdir
fs.mkdir(path[, mode], callback) 要求父目录必须存在 let fs = require('fs'); fs.mkdir('./c/b/a', res=>{ // ...
- java web 增加信息课堂测试00
按照图片要求设计添加新课程界面.(0.5分)在后台数据库中建立相应的表结构存储课程信息.(0.5分)实现新课程添加的功能.要求判断任课教师为王建民.刘立嘉.刘丹.王辉.杨子光五位教师的其中一位.(0. ...
- 运行biggan demo
http://www.zhuanzhi.ai/document/8705953a704e1bf8e051c161d1587d88
- 安装memcached和elasticsearch服务并systemctl管理
[root@izbp18dv3a3metugyd02qxz bin]# rpm -qa | grep memcache [root@izbp18dv3a3metugyd02qxz bin]# yum ...
- [BZOJ4558]:[JLoi2016]方(容斥+模拟)
题目传送门 题目描述 上帝说,不要圆,要方,于是便有了这道题.由于我们应该方,而且最好能够尽量方,所以上帝派我们来找正方形上帝把我们派到了一个有N行M列的方格图上,图上一共有$(N+1)\times ...
- (转)CBC模式和ECB模式解读
一 什么是CBC模式 CBC模式的全称是Cipher Block Chaining模式(密文分组链接模式),之所以叫这个名字,是因为密文分组像链条一样相互连接在一起. 在CBC模式中,首先将明文分组与 ...
- 【转】C++ 模板类的声明与实现分离问题
链接如下: https://www.cnblogs.com/tonychen-tobeTopCoder/p/5199655.html
- PHP执行外部程序
备份/恢复数据库 exec - 执行一个外部程序(在php文件所在目录进行执行) 很久以前写的,很多方法是项目中的直接复制粘体用不了,只能提供下思路. 用到执行外部程序的就这一句: exec(&quo ...
- leetcode 46 全排列 (python)
给定一个没有重复数字的序列,返回其所有可能的全排列. 示例: 输入: [1,2,3]输出:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]] ...
- js将html转换为纯文本
document.body.textContent//firefox浏览器 document.body.innerText//适用ie webkit浏览器 document.body.innerHTM ...