凹槽最大水容量
来源:互联网 发布:淘宝成功案例 编辑:程序博客网 时间:2024/04/28 08:58
Trapping Rain Water
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
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
思路:
对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i](均不包含自身)。
如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。
有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight。
时间复杂度是O(n)。
public class Solution {
public int trap(int[] A) {
if(A == null || A.length < 1)
return 0;
int maxheight = 0;
int[] leftMostHeight = new int[A.length];
for(int i =0; i < A.length; i++) {
leftMostHeight[i] = maxheight;
maxheight = maxheight > A[i] ? maxheight : A[i];
}
maxheight = 0;
int[] rightMostHeight = new int[A.length];
for(int i =A.length - 1; i>=0; i--) {
rightMostHeight[i] = maxheight;
maxheight = maxheight > A[i] ? maxheight : A[i];
}
int water = 0;
for(int i =0; i < A.length; i++)
{
int high = Math.min(leftMostHeight[i], rightMostHeight[i]) - A[i];
if(high>0)
water += high;
}
return water;
}
}
解法二:
是两边往中间遍历,
记录当前第二高点secHight,
然后利用这个第二高点减去当前历经的柱子,
剩下就装水容量了;
两边比较时,最高的点不用动,只移动第二高点
public class Solution {
public int trap(int[] A) {
int secHight = 0;
int left = 0;
int right =A.length;
int area = 0;
while (left < right){
if (A[left] < A[right]){
secHight = Math.max(A[left], secHight);
area += secHight-A[left];//计算当前格的能装雨水的容量
left++;
} else {
secHight = Math.max(A[right], secHight);
area += secHight-A[right];
right--;
}
}
return area;
}
}
- 凹槽最大水容量
- 面试题:[Container the most water]容器中最大水容量
- LeetCode Trapping Rain Water等雨水的凹槽容量
- LeetCode - Trapping Rain Water 等雨水的凹槽容量
- [Leetcode] Container With Most Water 能装最大水的容量
- hdu 5112 排序+求最大水题
- LeetCode 11 Container With Most Water(最大水容器)
- nyoj 7 街区最短路径问题【大水】
- 带凹槽的塑料直尺
- 凹槽型光电开关WTK-10
- 大水题!!!
- 大水题
- 最直观的U盘 一眼就能看出容量
- 深色金属板的各种凹槽与突起
- 大水的遗言
- poj 1656 大水题
- POJ 2328 大水题
- hdu 4247 大水题
- avi文件结构
- EOJ 2067 最小生成树
- 内存泄露
- HTTP协议学习笔记
- 条件随机场介绍
- 凹槽最大水容量
- 数据结构实验之查找六:顺序查找
- Selenium2(JAVA)环境搭建
- 手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis
- NYOJ-畅通工程
- HDU-4292-网络流最大流
- Ananagrams Uva156
- Base入门篇
- 02C#一些基础知识