Algorithms—42.Trapping Rain Water
来源:互联网 发布:友盟app数据统计 编辑:程序博客网 时间:2024/05/21 07:14
public class Solution { public int trap(int[] height) { if (height.length<=1) {return 0;} int a=0; int h=height[a]; /** * 求出最高峰 */ for (int i = 1; i < height.length; i++) { if (height[i]>h) {a=i;h=height[i];}} Map<String, Integer> leftMap=new HashMap<String, Integer>(); Map<String, Integer> rightMap=new HashMap<String, Integer>(); leftMap.put("result", 0); leftMap.put("a",a); rightMap.put("result", 0); rightMap.put("a",a); Map<String, Integer> leftrRsult=new Solution().left(leftMap, height); Map<String, Integer> rightResult=new Solution().right(leftMap, height); return leftrRsult.get("result")+rightResult.get("result"); } /** * 求左侧 * @param height * @param a * @return */ public Map<String, Integer> left(Map<String, Integer> m,int[] height){ Map<String, Integer> map=new HashMap<String, Integer>(); if (m==null||m.get("a")==null) {return m;} if (m.get("a")<=1) {return m;} int h=height[0]; int result=m.get("result"); int sum=0; int a=0; for (int i = 1; i <m.get("a"); i++) {if (height[i]<h) {sum+=(h-height[i]);}else {sum=0;h=height[i];a=i;}} result+=sum; map.put("result", result); map.put("a", a); return left(map, height); } /** * 求右侧 * @param height * @param a * @return */ public Map<String, Integer> right(Map<String, Integer> m,int[] height){ Map<String, Integer> map=new HashMap<String, Integer>(); if (m==null||m.get("a")==null) {return m;} if (m.get("a")>=height.length-2) {return m;} int h=height[height.length-1]; int result=m.get("result"); int sum=0; int a=0; for (int i = height.length-1; i>m.get("a"); i--) {if (height[i]<h) {sum+=(h-height[i]);}else {sum=0;h=height[i];a=i;}} result+=sum; map.put("result", result); map.put("a", a); return right(map, height); }}
思路:先找出最高峰,然后分为左右两个部分,以左边为例说明,从开始端作为参照开始往右遍历,如果遇到小于参照值的,那么加上参照值与当前值的差值,否则更换参照值;求出靠近最高峰最大值之间的蓄水量,然后递归进行再次求解。右边同理。
0 0
- Algorithms—42.Trapping Rain Water
- LeetCode Algorithms 42. Trapping Rain Water
- 42.Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- 42. Trapping Rain Water
- Bash processing pipeline
- Hadoop Hbase数据库操作
- Java 书籍
- hdu(2795)——Billboard(简单的线段树的询问,以及建树的技巧)
- shell学习十九天----文本块排序
- Algorithms—42.Trapping Rain Water
- navicat for mysql导出导入数据库
- 周国平:孤独的价值
- NA心得
- 一名普通的电脑技术员的蓝光历程
- 网络攻击常用手段
- 文件系统(四)--pipe.c read_write.c stat.c fcntl.c ioctl.c源码分析
- 字母统计
- 实现Web安全登录