Trapping Rain Water
2016-03-16 20:24
260 查看
Given n[/i] 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
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[/b] for contributing this image!
来源: <https://leetcode.com/problems/trapping-rain-water/>
分析空间复杂度O(n)对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;2. 从右往左扫描一遍,对于每个柱子,求最大右值;3. 再扫描一遍,把每个柱子的面积并累加。
[/code]
也可以,该方法空间复杂度O(1)1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;2. 处理左边一半;3. 处理右边一半。
[/code]
来自为知笔记(Wiz)
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. Thanks Marcos[/b] for contributing this image!
来源: <https://leetcode.com/problems/trapping-rain-water/>
分析空间复杂度O(n)对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;2. 从右往左扫描一遍,对于每个柱子,求最大右值;3. 再扫描一遍,把每个柱子的面积并累加。
class Solution {
public:
int trap(vector<int>& height) {
int length=height.size();
int *max_left=new int[length]();
int *max_right=new int[length]();
for(int i=1;i<length;i++){
max_left[i]=max(max_left[i-1],height[i-1]);
max_right[length-i-1]=max(max_right[length-i],height[length-i]);
}
int sum=0;
for (int i=0;i<length;i++){
int h=min(max_left[i],max_right[i]);
if(h>height[i])
sum+=h-height[i];
}
delete[]max_left;
delete[]max_right;
return sum;
}
};
[/code]
也可以,该方法空间复杂度O(1)1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;2. 处理左边一半;3. 处理右边一半。
class Solution {
public:
int trap(vector<int>& height) {
int max = 0; // 最高的柱子,将数组分为两半
int n=height.size();
for (int i = 0; i < n; i++)
if (height[i] > height[max]) max = i;
int water = 0;
for (int i=0,peak=0;i<max;i++){
if(peak<height[i])peak=height[i];
else
water+=peak-height[i];
}
for(int j=n-1,peak=0;j>max;j--){
if(peak<height[j])peak=height[j];
else
water+=peak-height[j];
}
return water;
}
};
[/code]
来自为知笔记(Wiz)
相关文章推荐
- Android垂直同步信号VSync的产生及传播结构详解
- android:taskAffinity与android:finishOnTaskLaunch之我见
- iOS之05-三大特性之封装
- Android轻量缓存框架--ASimpleCache
- Android课程---首学开发
- 使用工具来提升Android开发效率
- Android APP安装后不在桌面显示图标的应用场景
- Android 异常 [INSTALL_FAILED_NO_MATCHING_ABIS]
- Unity社交功能开发——语音聊天
- Core Motion 加速器的使用步骤
- iOS启动屏 ➕ 闪屏的方法
- 国内优秀Android学习资源
- Android中的5种数据存储方式
- LeetCode 202 Happy number
- ImageContainer重复添加,以及Map<String,Object>遍历
- Android开发中一些被冷落但却很有用的类和方法
- Android抓包分析-fiddler版
- Android图片加载
- android应用性能测试——cpu的占用率
- iOS多线程开发