Trapping Rain Water
来源:互联网 发布:淘宝怎么开发票 编辑:程序博客网 时间:2024/05/17 01:52
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.
对某个值A[i]来说,能trapped的最多的water取决于在i左边的最高的值leftHeight[i]和
在i右边的最高的值rightHeight[i]。那么在i这个位置上能trapped的water就是
min(left,right) – A[i]。有了这个想法就好办了,第一遍从左到右计算数组leftHeight,
第二遍从右到左计算rightHeight。时间复杂度是O(n)。
public class Solution { public int trap(int[] height) { int result=0,maxHeight=0;if(height==null||height.length<=2)return result;int[] left=new int[height.length];int[] right=new int[height.length];left[0]=maxHeight=height[0];for(int i=1;i<height.length;i++){maxHeight=maxHeight>height[i]?maxHeight:height[i];left[i]=maxHeight;}right[height.length-1]=maxHeight=height[height.length-1];for(int i=height.length-2;i>=0;i--){maxHeight=maxHeight>height[i]?maxHeight:height[i];right[i]=maxHeight;}for(int i=0;i<height.length;i++)result+= Math.min(left[i],right[i])-height[i];return result; }}
0 0
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- [LeetCode]Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- LeetCode-Trapping Rain Water
- Trapping Rain Water
- [leetcode] Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- 38 - Trapping Rain Water
- lsyncd实时同步搭建指南——取代rsync+inotify
- Online Judge System For SzNOI 题库 语法百题 C++ d017
- windows7下修改hosts文件无效解决办法(hbase连接失败)
- Android使用VideoView和MediaController播放网络视频(包括横竖排切换的处理)
- ld: warning: directory not found for option“XXXXXX”
- Trapping Rain Water
- Failure [INSTALL_FAILED_OLDER_SDK]解决办法
- *很不错*朴素贝叶斯分类器的应用
- GRE写作必备句型
- C# WPF button样式清空以及关闭 最小化 按钮重置
- 杭电1010
- iOS开发多线程篇—线程安全
- (转)主成分分析(Principal components analysis)-最大方差解释及
- Xcode 6 关于 iOS App 国际化问题