Trapping Rain Water
2016-07-14 09:02
323 查看
Given n non-negative integers representing an elevation map where the width of each bar is
Example
Given
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.
1, compute how much water it is able to trap after raining.
Example
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return
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 { /** * @param heights: an array of integers * @return: a integer */ public int trapRainWater(int[] A) { if (A == null || A.length <= 2) return 0; int maxIndex = 0; for (int i = 1; i < A.length; i++) { if (A[i] > A[maxIndex]) { maxIndex = i; } } int leftMax = A[0]; int total = 0; for (int i = 1; i < maxIndex; i++) { if (A[i] < leftMax) { total += (leftMax - A[i]); } else { leftMax = A[i]; } } int rightMax = A[A.length - 1]; for (int i = A.length - 2; i > maxIndex; i--) { if (A[i] < rightMax) { total += (rightMax - A[i]); } else { rightMax = A[i]; } } return total; } }
相关文章推荐
- Android 通用ListView、GridView适配器
- spring_applicationContext和beanFactory区别
- Android 布局文件Layout XML属性
- 【iCore3 双核心板_FPGA】实验二十一:Niosii——基于内部RAM建立第一个软核
- Android 广播 博客链接
- android studio for android learning (十六) support-annotations简介
- Android StringEntity() 和 UrlEncodedFormEntity() 的区别
- Swift解析Json返回值为null的问题
- Objective-C Posing
- 新app开发
- BroadcastReceiver
- 苹果iOS系统下的推送机制及实现
- Android 中文件类型与MIME的匹配表
- IOS atomic与nonatomic,assign,copy与retain的定义和区别
- Android-x86_64 - /system/xbin/log.sh
- Unity引擎中各个平台的调用路径
- 第三方登录-----Application
- Android-x86_64 - /system/etc/init.sh
- Objective-C是动态语言吗?为什么?
- Xcode 8 的 6 大新功能一览