【leetcode】Array——Trapping Rain Water(42)
2016-02-11 22:38
525 查看
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.
解题:
第一次尝试,一层一层找,虽然算法没错 但是time out了
网上资料:
找到制高点,然后分别从两端往中间遍历。
遍历的过程中记录局部的最高点,当前高度与局部最高点之间的差值就是当前位置的水量。
代码如下:
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
解题:
第一次尝试,一层一层找,虽然算法没错 但是time out了
网上资料:
找到制高点,然后分别从两端往中间遍历。
遍历的过程中记录局部的最高点,当前高度与局部最高点之间的差值就是当前位置的水量。
代码如下:
public int trap(int []height){ if(height.length<=2) return 0; //get max height int max_height = height[0]; int max_index = 0; for(int i=0;i<height.length;i++){ if(max_height<=height[i]){ max_height = height[i]; max_index=i; } } int result=0; int jubu_max_l=height[0]; for(int i=1;i<max_index;i++){ if(height[i]>=jubu_max_l) jubu_max_l = height[i]; else result += (jubu_max_l-height[i]); } int jubu_max_r =height[height.length-1]; for(int i=height.length-2;i>max_index;i--){ if(height[i]>=jubu_max_r) jubu_max_r=height[i]; else result += (jubu_max_r-height[i]); } return result; }
相关文章推荐
- App上线流程
- iOS之NSDate
- 积跬步至千里系列之九--Android系统设置(二)
- iOS之数据解析 (JSON 、XML)
- iOS之延时器(NSTimer)
- Android辅助功能AccessibilityService与抢红包辅助
- iOS之运行时(Runtime)
- Android - 自定义多击事件
- Unity 摄像机
- Android问题集:1、在清单文件中设置activity全屏,报错了!!
- 在android的状态栏(statusbar)中增加menu,home和back快捷键的方法
- cocos3D第十三节:骨骼点绑定
- Android中Service(服务)详解
- Android开发环境搭建及入门相关
- android通讯录实例(一)
- iOS 获取当前时间以及计算年龄(时间差)
- swift算法手记-10
- 微信支付之HTML5页面WAP端接入
- Android中的WebView常用用法
- cocos2d int, float, double, const char* 转string