leetcode hard模式专杀之42. Trapping Rain Water
来源:互联网 发布:apt install java 编辑:程序博客网 时间:2024/06/09 16:57
继续刷leetcode hard模式, 这题是我喜欢的类型,可能因为我空间想象力还行,这题在2次内通过oj,
思路如下: 可以这样想, 每个数字上方拖着的空间如果左边有墙,右边也有墙,那么这个水就流不出去,而墙可以用左边最高的数字和右边最高的数字来表示,例如位置i,左边最高墙是3,右边最高墙是4, 那么i上能托几格水呢?当然是min(3,4)-i啦,所以这个问题就转换为如何高效率地找出每个位置i的左边最高墙和右边最高墙来,
用两个hashmap来做就好了,这样时间复杂度可以控制在O(n)
思路就这么简单, 代码如下:
public class Solution { public int trap(int[] height) { int globalMax = 0; for(int k = 0; k<height.length; k++){ globalMax = Math.max(globalMax, height[k]); } // key is Map<Integer, Integer> leftMaxMap = new HashMap(); Map<Integer, Integer> rightMaxMap = new HashMap(); for(int i = 0; i<height.length; i++){ if(i==0){ leftMaxMap.put(i, 0); }else{ leftMaxMap.put(i, Math.max(leftMaxMap.get(i-1), height[i-1])); } } for(int j = height.length-1;j>=0;j--){ if(j==height.length-1){ rightMaxMap.put(j, 0); }else{ rightMaxMap.put(j, Math.max(rightMaxMap.get(j+1), height[j+1])); } } int face = 0; for(int m=0; m<height.length; m++){ int tmp = (Math.min(leftMaxMap.get(m), rightMaxMap.get(m))-height[m]); face+=tmp<=0?0:tmp; } return face; }}
阅读全文
0 0
- leetcode hard模式专杀之42. Trapping Rain Water
- Leetcode 42. Trapping Rain Water (Hard) (cpp)
- [hard]42. Trapping Rain Water
- 42. Trapping Rain Water[hard]
- [leetcode 42. Trapping Rain Water] Hard | Week 1
- [Leetcode 42, Hard] Trapping Rain Water
- Trapping Rain Water [hard]
- leetcode之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 42.Trapping Rain Water
- [Leetcode] 42. Trapping Rain Water
- [leetcode] 42.Trapping Rain Water
- 【leetcode】42. Trapping Rain Water
- CSDN-markdown编辑器使用手册
- Single Responsibility Principle 单一职责原则
- google 10年 java技术栈【全栈】
- SpringMVC源码(三)Controller控制器
- MyBatis中的批量删除操作
- leetcode hard模式专杀之42. Trapping Rain Water
- lambda表达式学习1
- Open Closed Principle 开放封闭原则
- flume学习:自定义拦截器
- 167. Two Sum II
- Ubuntu16.04 server下配置MySQL,并开启远程连接
- 014-java-005
- 应用的调试及adb命令的使用
- [PowerShell入门]选择结构和循环结构