leetcode解题方案--042--Trapping Rain Water
来源:互联网 发布:西部数据域名如何备案 编辑:程序博客网 时间:2024/06/08 15:51
题目
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.
类似题目,格板储水和美团直方图(栈)
对于每一个格子来说,其左侧的最高板和右侧的最高板决定了水的高度。
所以结合动态规划,分别遍历两次。得到的两个数组分别表示,这个格儿的左侧最高板和右侧最高板儿。
两个值取小,得到答案。
public static int trap(int[] height) { if (height.length<=2) { return 0; } int[] leftMax = new int[height.length]; int[] rightMax = new int[height.length]; leftMax[0] = height[0]; rightMax[height.length-1] = height[height.length-1]; for (int i = 1; i < height.length-1; i++) { leftMax[i] = Math.max(leftMax[i-1], height[i]); rightMax[height.length-i-1] = Math.max(rightMax[height.length-i], height[height.length-i-1]); }// System.out.print(Arrays.toString(leftMax));// System.out.print(Arrays.toString(rightMax)); int container = 0; for (int i = 1; i<height.length-1; i++) { int max = Math.min(leftMax[i], rightMax[i]); container = container+(max-height[i]); } return container; }
不知道为什么代码的字体和发布后的博客代码字体总是不一样,有知道的大佬麻烦留个言。
阅读全文
0 0
- leetcode解题方案--042--Trapping Rain Water
- leetcode-042:Trapping Rain Water
- LeetCode 042 Trapping Rain Water
- [LeetCode]042-Trapping Rain Water
- LeetCode 042 Trapping Rain Water
- [LeetCode]Trapping Rain Water,解题报告
- leetcode解题笔记-Trapping Rain Water
- 【LeetCode】Trapping Rain Water解题报告
- [LeetCode] Trapping Rain Water 解题报告
- [leetcode] 42. Trapping Rain Water 解题报告
- [Leetcode] 42. Trapping Rain Water 解题报告
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [LeetCode]Trapping Rain Water
- LeetCode-Trapping Rain Water
- 周立功键盘
- h5上下拉分页,基于iscroll.js+doT.js+ajax
- Item 5:了解C++默默编写并调用哪些函数【effective C++读书笔记】
- JS基础学习(八)
- python 最佳实践--常用小工具
- leetcode解题方案--042--Trapping Rain Water
- Protobuf windows安装使用
- 元素水平垂直居中
- Ubuntu学习——Error“E: Sub-process /usr/bin/dpkg returned an error code (1)”
- Nim游戏(Nim入门经典题)
- Linux 运行参数 一个减号与两个减号
- 配置多个mysql服务实例
- PNP : Distributed mean and median
- eclipse server Runtime Environment 环境配置