leetcode 42. Trapping Rain Water
来源:互联网 发布:联合国统计署数据库 编辑:程序博客网 时间:2024/05/22 09:45
//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 class Solution { public static void main(String[] aargs){int[] input = {0,1,0,2,1,0,1,3,2,1,2,1};int result = trap(input);System.out.println(result);}public static int trap(int[] height) { int result = 0; if(height == null || height.length == 0){ return result; } int[] leftMaxHeight = new int[height.length];//从左至右的当前最大高度 int[] rightMaxHeight = new int[height.length]; int leftMax = 0;//左侧当前的最大高度 int rightMax = 0; for (int i = 0; i < height.length; i++) {//从左至右扫描最大高度,并将其存入leftMaxHeight数组 leftMaxHeight[i] = leftMax; leftMax = Math.max(height[i], leftMaxHeight[i]); } for (int i = height.length - 1; i >= 0; i--) {//从右至左扫描最大高度,并将其存入rightMaxHeight数组 rightMaxHeight[i] = rightMax; rightMax = Math.max(height[i],rightMaxHeight[i]); } for(int i = 0;i<height.length;i++){ int min = Math.min(leftMaxHeight[i], rightMaxHeight[i]);//找到两个方向综合起来的最小高度 if(height[i]<min){//如果这个高度大于实际高度,则用这个高度减去实际高度就是本格可以装水的量 result = result+(min-height[i]); } } return result; } }
0 0
- [LeetCode]42.Trapping Rain Water
- LeetCode --- 42. Trapping Rain Water
- LeetCode 42.Trapping Rain Water
- [Leetcode] 42. Trapping Rain Water
- [leetcode] 42.Trapping Rain Water
- 【leetcode】42. Trapping Rain Water
- ***LeetCode 42. Trapping Rain Water
- Leetcode 42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- [LeetCode]42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- leetcode.42. Trapping Rain Water
- [leetcode] 42. Trapping Rain Water
- LeetCode-42.Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- 我
- HDU 1045 Fire Net
- 一个故事告诉你比特币的原理及运作机制_系统架构
- PDO总结
- 图吧地图夜间导航SDK接口应用案例
- leetcode 42. Trapping Rain Water
- 修改Tomcat服务的默认端口号
- DOM优化-笔记
- hibernate缓存机制详细分析
- ButterKnife替代findViewById
- CSS---Tips1文本样式
- 在linux下使用curl访问 多参数url GET参数问题
- c 空指针
- 创建GitHub技术博客全攻略