雨水,lintcode
来源:互联网 发布:linux 退出vi 编辑:程序博客网 时间:2024/04/28 19:03
给出 n 个非负整数,代表一张X轴上每个区域宽度为 1 的海拔图, 计算这个海拔图最多能接住多少(面积)雨水。
样例
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.
一刷没有ac
解题思路:用两个指针像中间夹,记录左右保持的左最大和右最大,每次判断两者大小向中间移动,移动的时候计算res。时间O(n),空间O(1)。
public class Solution { /** * @param heights: an array of integers * @return: a integer */ public int trapRainWater(int[] heights) { int res = 0; if(heights == null || heights.length == 0) return res; int lmax = 0, rmax = 0; int l = 0; int r = heights.length-1; while(l < r){ lmax = Math.max(lmax, heights[l]); rmax = Math.max(rmax, heights[r]); if(lmax > rmax){ res += rmax - heights[r]; r--; }else{ res += lmax - heights[l]; l++; } } return res; }}
如果考虑时间O(n),空间O(n)的话,可以从左遍历纪录最大,然后从右遍历,开始计算右最大,在两者中取最小,在某点的水量应该是两者最小和此处高度的差
public class Solution { /** * @param heights: an array of integers * @return: a integer */ public int trapRainWater(int[] heights) { if(heights == null || heights.length == 0) return 0; int[] res = new int[heights.length]; int max = 0; for(int i = 0; i < heights.length; i++){ max = Math.max(max, heights[i]); res[i] = max; } max = 0; int result = 0; for(int i = heights.length - 1; i >= 0; i--){ max = Math.max(max,heights[i]); result += Math.min(max, res[i]) - heights[i]; } return result; }}
0 0
- 雨水,lintcode
- LintCode-接雨水
- LintCode:接雨水
- LintCode:接雨水
- 接雨水 lintcode
- lintcode[363]:接雨水
- LintCode:M-接雨水
- 接雨水-LintCode
- 接雨水 II-LintCode
- LintCode rain trap 接雨水
- [LintCode 363] 接雨水(Python)
- **[Lintcode]Trapping Rain Water 接雨水
- lintcode刷题——接雨水
- 接雨水
- 接雨水
- 接雨水
- 陷阱雨水:
- 伤心的雨水
- 正斜杠“/”与反斜杠”\”
- 异常
- route学习
- ios 获取当前控制器的方法
- JavaScript入门(一)
- 雨水,lintcode
- SpringMvc教程(五)--父子上下文(WebApplicationContext)
- Java 实现简单的UDP通信
- 腾讯大数据平台质量保障之道
- MySQL基本知识
- 设计中的版面艺术!你造吗?(五)
- 组合数学 Catalan Number 总结
- 用fpm来做rpm打包
- 修改toolbar自适应报表宽度