Trapping Rain Water
2015-07-31 10:05
316 查看
问题描述
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
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!
解决思路
假设数组的长度为len,(1) 找到最高的那个柱子highest;
(2) 双指针:从0到highest, 从len-1到highest;
(3) 辅助栈s:存的是柱子高度的升序序列,如果遇到比栈顶元素小的高度,则能够储存水量为s.peek()-cur
时间空间复杂度均为O(n).
程序
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. Thanks Marcos for contributing this image!
解决思路
假设数组的长度为len,(1) 找到最高的那个柱子highest;
(2) 双指针:从0到highest, 从len-1到highest;
(3) 辅助栈s:存的是柱子高度的升序序列,如果遇到比栈顶元素小的高度,则能够储存水量为s.peek()-cur
时间空间复杂度均为O(n).
程序
public class Solution { public int trap(int[] height) { if (height == null || height.length == 0) { return 0; } int highest = getHighestIdx(height); int water = 0; Stack<Integer> s = new Stack<Integer>(); for (int i = 0; i < highest; i++) { if (s.isEmpty() || height[i] > s.peek()) { s.push(height[i]); } else { water += s.peek() - height[i]; } } s = new Stack<Integer>(); for (int i = height.length - 1; i > highest; i--) { if (s.isEmpty() || height[i] > s.peek()) { s.push(height[i]); } else { water += s.peek() - height[i]; } } return water; } private int getHighestIdx(int[] height) { int high = 0; int idx = 0; for (int i = 0; i < height.length; i++) { if (height[i] > high) { high = height[i]; idx = i; } } return idx; } }
相关文章推荐
- android studio 升级后报错
- Android开发:自定义GridView/ListView数据源
- android ndk 开发流程以及“Method could not be resolved”的解决办法,代码提示
- Android图像处理
- Android Studio引用jar及so文件
- AndroidManifest.xml文件详解(uses-configuration)
- android usb 通信
- android开发环境 国内镜像 及Android SDK manager使用国内服务器方法
- ABP(现代ASP.NET样板开发框架)系列之15、ABP应用层——应用服务(Application services)
- Android Api Demos登顶之路(十二)Presentation
- cocos2dx中的retain和release
- Handler介绍及简单使用
- android 收集已发布版本的错误信息(UncaughtExceptionHandler)
- Unity3D 图片模糊
- Android shape & selector
- Android ble 蓝牙4.0 总结
- Android弹出菜单
- 被墙后如何获取android源代码
- xcode找到App的scheme,只出现mac的scheme
- everything is a object2